1. 程式人生 > >物件流Object ,物件要先序列化才能寫入;

物件流Object ,物件要先序列化才能寫入;

import java.io.Serializable;
//先寫出一個Student類方便new物件 ,重寫toString方法方便輸出;
public class Student implements Serializable{
//這裡要實現Serializable介面,這是標記介面,類似 colenable介面;告訴程式該物件可被序列化;

private static final long serialVersionUID = 1L;
//ID用途可以在修改物件的屬性的時候另一邊輸出不會報錯,增加或者修改的引數會預設為初始值;

private String name;
private int num;

public Student(String name, int num) {
super();
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "Student [name=" + name + ", num=" + num + "]";
}

}

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TestObject {
static String []s = {"自動","都是","大方","感受到"};
static String s1 = "sfsfsgfsgsgs";
static Student s2 = new Student("李上",22);
static Student s3 = new Student("發的",22);
static Student s4 = new Student("風扇",22);
static Student s5 = new Student("df",22);
//new出物件,也可以直接把物件挨個寫入檔案中,再挨個讀出來;
//當用while讀取多個物件時候要用到while(Objiet!=null) {}
//程式會在讀取到最後一個的時候繼續讀取下一個,然後報錯,預防的方法是
//在寫入時候最後寫入一個null物件,當讀取到null時候程式就會跳出迴圈;

public static void main(String[] args) {
TestObject t =new TestObject();

t.testw();
t.testr();

}
public void testw() {
File f = new File("G:\\demo\\x.txt");
List<Student> ls = new ArrayList<>();
ls.add(s2);
ls.add(s3);
ls.add(s4);
ls.add(s5);
//把物件放入集合中

ObjectOutputStream oos =null;
try {
oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(ls);
//把整個集合寫入檔案之中;
System.out.println();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



public void testr() {
File f = new File("G:\\demo\\x.txt");

ObjectInputStream ois =null;
try {
ois = new ObjectInputStream(new FileInputStream(f));
List<Student> ls=  (List<Student>) ois.readObject();
//讀取時候要注意輸出物件的型別,放入什麼型別就要用什麼型別來接收;
System.out.println(ls);
//列印時候也要注意物件型別的轉化;

} 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();
}finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

//最後要注意在使用完流之後要使用close();方法關閉;