物件流(objectInputStream 和ObjectOutputStream)
阿新 • • 發佈:2018-12-16
一、對面序列化過程 :將記憶體中的物件通過ObjectOutputStream轉為二進位制流,儲存在硬碟檔案中
對面序列化要滿足的條件
1、物件所對應的類要實現Serializable介面
2、類的屬性同樣要實現Serializable介面
3、凡是實現Serializable介面都有一個表示序列化版本識別符號的靜態變數:
private static final long seriaVersionUID;來表示不同版本間的相容性,
如果沒有顯示定義這個靜態變數,它的值是Java執行時環境根據類的內部細節自動生成的,若類的原始碼作了修改
,seriaVersionUID可能發生變化。建議顯示宣告。 確保不同版本相同的serialVersionUID.
- public void text(){
- File f2=new File("C:\\Users\\ASUS\\Desktop\\hello3.txt"); //儲存路徑
- people p=new people("12","花花");
- ObjectOutputStream f3=null;
- try {
- f3 = new ObjectOutputStream(new FileOutputStream(f2));
- f3.writeObject(p);
- f3.flush();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- try {
- f3.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class people implements Serializable{
- public String name;
- public String arg;
- public people(String name,String arg){
- this.name=name;
- this.arg=arg;
- }
- public String toString(){
- return "people [name ="+name+",arg=" +arg+"]";
- }
- }
二、對面反序列化過程:將硬碟中的檔案通過objectInputStream轉換為相應的物件
- public void textInput(){
- ObjectInputStream f=null;
- people p=null;
- try {
- f = new ObjectInputStream(new FileInputStream("C:\\Users\\ASUS\\Desktop\\hello3.txt"));
- p = (people)f.readObject();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(p);
- try {
- f.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- class people implements Serializable{
- public String name;
- public String arg;
- public people(String name,String arg){
- this.name=name;
- this.arg=arg;
- }
- public String toString(){ //輸出
- return "people [name ="+name+",arg=" +arg+"]";
- }
- }