---------------------- java
package com.io.file; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /* * 對對象進行操做,把對象數據存入到文件中,再從文件中讀取 */ public class Object_in_out { public static void main(String[] args) { try { // write(); read(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void read() throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream ois=new ObjectInputStream(new FileInputStream("g:/java/object.txt")); Person p=(Person)ois.readObject(); System.out.println(p.getName()+",,,,,,,,"+p.getAge()); ois.close(); } public static void write() throws FileNotFoundException, IOException{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("g:/java/object.txt")); oos.writeObject(new Person("aaa",33));//把對象寫入到文件中 oos.close(); } } class Person implements Serializable{//注意這個對象類要實現Serializable序列化接口 //此接口會爲該對象生成一個根據該對象的序列化id,若是本對象改變了,調用本對象的類要從新編譯才行 //或者直接指定本對象的序列化id public static final long serialVersionUID = 42L;//爲本對象生成一個固定的系列化id,這樣本類改變的話,調用類就不用從新編譯了 private String name; public static String country="";//注意這裏,靜態不能序列化,由於序列化的在對內存中,而靜態在方法區中 private int age; //若是不想被序列化,但又不定義靜態,能夠用transient關鍵字修飾,保證被修飾的能夠在對內存中存在,但不能存放到文本文件中 //如這樣定義就能夠了:private transient int ages; public Person(String name,int age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }