将若干个Student对象添加到List集合中,然后将List存储到txt文件中,再从 txt文件读取内容,并且打印List的完整代码
时间: 2024-04-11 08:26:04 浏览: 107
以下是将Student对象添加到List集合中,将List存储到txt文件中,再从txt文件读取内容并打印List的完整代码示例:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Alice", 18));
studentList.add(new Student("Bob", 20));
studentList.add(new Student("Charlie", 22));
// 将List集合中的内容写入txt文件
try {
FileWriter fileWriter = new FileWriter("students.txt");
BufferedWriter writer = new BufferedWriter(fileWriter);
for (Student student : studentList) {
writer.write(student.getName() + "," + student.getAge());
writer.newLine();
}
writer.close();
System.out.println("List已成功写入txt文件。");
} catch (IOException e) {
System.out.println("写入txt文件时出现错误:" + e.getMessage());
}
// 从txt文件中读取内容并打印List
List<Student> newList = new ArrayList<>();
try {
FileReader fileReader = new FileReader("students.txt");
BufferedReader reader = new BufferedReader(fileReader);
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0];
int age = Integer.parseInt(parts[1]);
Student student = new Student(name, age);
newList.add(student);
}
reader.close();
System.out.println("从txt文件中读取的List内容:");
for (Student student : newList) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge());
}
} catch (IOException e) {
System.out.println("读取txt文件时出现错误:" + e.getMessage());
}
}
}
```
您可以将以上代码保存为一个Java文件,然后运行它,即可实现将Student对象添加到List集合中,将List存储到txt文件中,并从txt文件读取内容并打印List。
阅读全文