如何将一个Java对象序列化到文件里?

将对象序列化到文件

1)对象需要实现Seralizable接口
public class StudentBean implements Serializable {
······
}

2)通过ObjectOutputStream的writeObject()方法写入
和ObjectInputStream的readObject()方法来进行读取

//存进去
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("D:/student.txt"));
os.writeObject(studentList);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//读出来
try {
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("D:/student.txt"));
ArrayList<StudentBean> list = new ArrayList<StudentBean>();
list = (ArrayList<StudentBean>) is.readObject();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容