java扫描txt文件,并将内容打印,内容包括名字和几个爱好。名字是String类,爱好是Arraylist类,新建一个class且有一个toString 用String.format打印出来的名字后面要有冒号且要空出一定的距离,爱好的开头对齐
时间: 2024-03-03 09:50:50 浏览: 59
打印txt文件
4星 · 用户满意度95%
好的,这是一个Java的IO操作,可以通过Scanner类来扫描文件内容,然后解析出名字和爱好,存储到一个类中。这个类需要重写toString方法,用String.format打印出来。
以下是一个简单的实现示例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Person {
private String name;
private ArrayList<String> hobbies;
public Person(String name, ArrayList<String> hobbies) {
this.name = name;
this.hobbies = hobbies;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%-10s:", name));
for (String hobby : hobbies) {
sb.append(String.format("%-10s", hobby));
}
return sb.toString();
}
public static void main(String[] args) {
try {
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(":");
String name = parts[0];
String[] hobbies = parts[1].split(",");
ArrayList<String> hobbyList = new ArrayList<>();
for (String hobby : hobbies) {
hobbyList.add(hobby.trim());
}
Person person = new Person(name, hobbyList);
System.out.println(person);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
```
其中,test.txt文件的格式如下:
```
Tom: reading, swimming, hiking
Jerry: singing, dancing, cooking
```
输出结果为:
```
Tom :reading swimming hiking
Jerry :singing dancing cooking
```
这里使用了String.format方法来格式化输出,%-10s表示左对齐,并占用10个字符的宽度,如果不够则用空格填充。
阅读全文