2014-02-17 14 views
-1

我想從一個對象文件中編寫和讀取一個可序列化的類。我可以將這個對象寫入一個文件,但我似乎無法將對象讀回並寫入控制檯。從文件中讀取序列化對象?

這兩個選項都不起作用。我只想讀取對象,因爲它被寫入對象文件。

代碼嘗試:

public void readBinary1() throws IOException, ClassNotFoundException { 
     ObjectInputStream input = new ObjectInputStream(new FileInputStream 
             ("G:\\testobject.tmp")); 
     input.readObject(); 

     System.out.println(new myClass()); 
    } 

    public void readBinary1() throws IOException, ClassNotFoundException { 
     ObjectInputStream input = new ObjectInputStream(new FileInputStream 
             ("G:\\testobject.tmp")); 

     System.out.println(new myClass(input.readObject())); 
    } 

類:

class myClass implements Serializable { 
    myClass() {} 

    myClass(myClass b) { 
     this.a = b.a; 
     this.b = b.b; 
    } 

    private static final long serialVersionUID = 1L; 
    private int a = 0; 
    private int b = 100; 
    private transient int c = 50; 
} 

程式碼:

I had to add a toString to my class to do it the way that it was suggested to do. That seems to be the way that is easiest in the short run but I would rather write the object and then be able to read in the object with out having to use the toString. Is there a way that I can read in the object with one read and then be able to break the info apart with the .dot notation. Such as mc.variable1 and mc.variable2 and so on. I had to type cast the read object also before the code would compile. 

有幾個輸入和輸出流的,允許用於對象的序列化到文件。我確信有不同的方式來包裝類的閱讀,並想知道哪種方式是創建閱讀的最佳方式。

+1

嘗試搜索在堆棧溢出這樣的問題 - 你確實有很多類似的問題和答案。 –

+0

看到http://stackoverflow.com/questions/17293991/how-to-write-and-read-java-serialized-objects-into-a-file – michael

+0

你似乎不明白你正在閱讀*序列化對象*來自流。 'MyClass mc =(MyClass)input.readObject();'。完成。 –

回答

1

這樣做:

myClass readedObject = (myClass) input.readObject(); 
System.out.println(readedObject);