2015-08-08 61 views
0

序列化碼是否能夠讀取內容中的任何類型對象的java toString方法?

public class JavaSerialization 
{ 


public static void main(String args[]) 
{ 
    serial s = new serial("This is serialization test."); 

    try 
    { 
     FileOutputStream fos = new FileOutputStream("mytext.txt"); 

     ObjectOutputStream oos = new ObjectOutputStream(fos); 

     oos.writeObject(s); 
    } 

    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 
} 

class serial implements Serializable 
{ 
private String s; 

private static final long serialVersionUID = 4616307934661308622L; 

public serial(String s) 
{ 
    this.s = s; 
    System.out.println("Output of Serilization : "+s); 
} 


@Override 
public String toString() 
{ 
    return s; 
} 

} 

反序列化碼

public class JavaDeserialization 
{ 

public static void main(String args[]) 
{ 

    try 
    { 
     FileInputStream fis = new FileInputStream("mytext.txt"); 

     ObjectInputStream ois = new ObjectInputStream(fis); 

     serial s = (serial)ois.readObject(); 

     System.out.println("deserialization :"+s.toString()); 
    } 

    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 
} 
+0

你的問題還不清楚。序列化不是由'toString()'完成的,所以不清楚你的代碼與你的實際問題有什麼關係。 – RealSkeptic

回答

0

一個toString()是像任何其他的方法,它可以訪問任何的任何其它方法都可以訪問。如果您可以獲取對希望訪問的對象的引用,則很可能可以訪問任何您想要的內容。

如果你問你的toString()是否可以工作,最好的方法是嘗試一下,但你可以這樣做。

注意:如果您讓緩衝輸出流未刷新並且未關閉,則會丟失部分結果,可能會丟失所有數據。

我建議你在完成或使用try-with-resource結構時使用資源close()

public static void main(String[] args) throws IOException { 
    Serial s = new Serial("This is serialization test."); 

    try(ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream("mytext.txt")){ 
     oos.writeObject(s); 
    } 
} 
相關問題