[英]Writing an object to a file
我需要將整個對象寫入文件並在需要時進行檢索。 假設我想編寫一個“學生”類的對象,該對象具有諸如成績,姓名,名冊等屬性。當我以后想在需要時訪問和操縱這些屬性時。 你能告訴我一種方法嗎?
使用ObjectOutputStream。
public class Student implements Serializable {
}
FileOutputStream fos = new FileOutputStream("Students.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student someStudent = new Student();
oos.writeObject(someStudent);
oos.close();
像這樣
嘗試序列化 。
做您要尋找的最簡單的方法是對象序列化。
基本上,您將一個接口添加到您的Student
類Serializable
,這將使您可以將該類的對象傳遞給ObjectOutputStream
。 您可以使用此流將這些學生寫入磁盤上的文件。 以后,可以通過ObjectInputStream
讀取它們,然后再次進行修改。
查看Java序列化API 。
如果您有簡單的JavaBean,則可以使用java.beans.XMLEncoder / XMLDecoder。
還有一種方法是使用JAXB。
最簡單的方法是簡單地實現Java的Serializable接口: http : //download.oracle.com/javase/1.4.2/docs/api/java/io/Serializable.html
public class Student implements Serializable {
}
然后,您可以使用readObject / writeObject方法進行讀取/寫入。
這些方法應該可以為您提供幫助,您的學生班級必須實現可序列化,使用方式如下:
學生s1 =新的Student(); objectToFile(“ test.ser”,s1); 學生s2 = fileToObject(“ test.ser”);
public static void objectToFile(String fileName, Serializable object){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
oos.writeObject(object);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try {
oos.flush();
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static Object fileToObject(String fileName){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)));
return ois.readObject();
} catch (Exception e) {
return null;
} finally{
try {
ois.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.