将对象的数组列表保存在txt文件中



我有一个txt文件,其中包含用于填充对象数组列表的数据对象示例:

public class Student implements Serializable 
{
protected String name;
protected int number;
...
}

我已经实现了一种读取文本文件的方法,该文件包含创建对象和填充数组列表所需的数据txt文件示例:

Matt,5
John,9
...

在阅读了txt文件,并将另一个学生添加到数组列表后,我如何用新学生更新txt文件?

编辑:我用来从txt文件中读取的代码

private ArrayList<Student> loadTextFileStudent(String filename) {
ArrayList<Student> students= new ArrayList();

File f = new File(filename);
if (f.exists() && f.isFile()) {
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {

String[] s = line.split(",");
if (s.length!=0) {
String name;
int number;
try 
{
name= s[0];
number= Integer.parseInt(s[1]);
} catch (NumberFormatException e) {
System.out.println("Error");
name="";
number= 0;
}
Student temp=new Student(name,number);
students.add(temp);
}
}
br.close();
} catch (FileNotFoundException ex) {
System.out.println("Error opening file.");
} catch (IOException ex) {
System.out.println("Error reading file.");
} catch (Exception e) {
System.out.println("ERROR");
e.printStackTrace();
}
} else {
System.out.println("File not found.");
}
return students;
}

您只需创建一个同名的新文件,并写入arrayList中的所有内容。

最新更新