MENU

ObjectIo

June 29, 2018 • Read: 122 • Java

  • 直接将Object写入或写出

    • TestObjectIo.java
    • translent关键字
    • serializable接口
    • extermalizable接口
import java.io.*;
public class TestObjectIo {

    public static void main(String[] args)  {
        T t = new T();
        try{
            FileOutputStream fos = 
                    new FileOutputStream("D:/testIo.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(t);
            oos.flush();
            oos.close();
            FileInputStream fis = new
            FileInputStream("D:/testIo.txt");    
            ObjectInputStream ois = new
            ObjectInputStream(fis);
            T tReaded = (T)ois.readObject();
            System.out.println(tReaded.i + " " + tReaded.j +
            " " + tReaded.d + " " + tReaded.s);
            //打印 10 9 0.0 false
        
        }catch(IOException e) {
            e.printStackTrace();
        }catch(ClassNotFoundException c) {
            c.printStackTrace();
        }
}
}
class T 
    implements Serializable{
    int i = 10;
    int j = 9;
    transient double d = 2.3;
    boolean s = true;
}

 T类的成员中有一个transient修饰的变量,transient意思是透明的,打印时会打印其所属变量类型的默认值,double的默认值是0.0,如果给boolean类型修饰,就会打印false

 Serializable中没有任何方法,只是为了给实现这个接口的类标记为“可序列化”的

Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment