java序列化

import java.io.*;
public class Cat implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
    public Cat () {
    	this.name = "new cat";
    }
    public String getName() {
    	return this.name;
    }
    public void setName(String name) {
                this.name = name;
    }
    
    
    public static void main(String[] args) {         
    	Cat cat = new Cat();
        try {
        	FileOutputStream fos = new FileOutputStream("catDemo.out");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            System.out.println(" 1> " + cat.getName());
            cat.setName("My Cat");                       
            oos.writeObject(cat);
            oos.close();                       
        } catch (Exception ex) {  ex.printStackTrace();   }
        
        try {
        	FileInputStream fis = new FileInputStream("catDemo.out");
            ObjectInputStream ois = new ObjectInputStream(fis);
            cat = (Cat) ois.readObject();
            System.out.println(" 2> " + cat.getName());
            ois.close();
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
    }
}//writeObject和readObject自己就是線程安全的,傳輸過程當中是不容許被併發訪問的。因此對象能一個一個接連不斷的傳過來
相關文章
相關標籤/搜索