保存文件
public void SaveFile(List users,String filename) throws IOException {
File file = new File(filename);
//创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
//创建对象输出流
ObjectOutputStream oos =new ObjectOutputStream(fos);
//保存对象
oos.writeObject(users);
}
读取文件
public ArrayList loadFile(String filename) throws IOException, ClassNotFoundException {//file 为写入的文件
File file = new File(filename);
if(file.length()>0) {
//创建文件输入流
FileInputStream fis = new FileInputStream(file);
//创建对象输入流
ObjectInputStream ois = new ObjectInputStream(fis);
//读取文件中的对象
ArrayList h2 = (ArrayList) ois.readObject();
//遍历list
for (int i = 0; i < h2.size(); i++) {
System.out.println(h2.get(i));
}
System.out.println("success");
return h2;
}else {
//第一次添加时文件为空,返回空值
System.out.println("null");
return null;
}
}