如何将一个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 list = new ArrayList();
list = (ArrayList) 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();
}

你可能感兴趣的:(如何将一个Java对象序列化到文件里?)