2011-06-02 139 views
-1

這可能是一個愚蠢的問題,但我想將2維字符串數組轉換爲java中的可序列化對象。做這個的最好方式是什麼?轉換爲可序列化的對象

+0

從下面發佈的錯誤消息可以明顯看出,您的問題與序列化無關。 -1。 – EJP 2011-06-02 09:01:34

+0

String,String []和String [] []都是可序列化的。 – 2011-06-02 09:28:09

回答

7

數組已經可序列化。 String也是。你不需要更多。

下面是一個完整的例子:

import java.io.*; 
import java.util.Arrays; 

/** 
* @author Colin Hebert 
*/ 
public class Serial { 

    public static void main(String[] args) 
      throws IOException, ClassNotFoundException { 
     PipedOutputStream pos = new PipedOutputStream(); 
     PipedInputStream pis = new PipedInputStream(pos); 

     String[][] strings = new String[][]{{"q","w","e"},{"a","s","d"},{"z", 
       "x","c"}}; 

     serialize(strings, pos); 

     String[][] strings2 = deserialize(pis); 

     System.out.println(Arrays.deepEquals(strings, strings2)); 
    } 

    public static String[][] deserialize(InputStream is) 
      throws IOException, ClassNotFoundException { 
     ObjectInputStream ois = new ObjectInputStream(is); 
     return (String[][]) ois.readObject(); 
    } 

    public static void serialize(String[][] array, OutputStream os) 
      throws IOException { 
     ObjectOutputStream oos = new ObjectOutputStream(os); 

     oos.writeObject(array); 
     oos.flush(); 
    } 
} 

資源:

+0

謝謝,我問這個問題的原因是因爲即時通訊製作Web服務和入口點需要一個字符串[] []作爲參數,但是當我使用Web服務進行測試時,我總是得到這個異常 – Davey 2011-06-02 08:48:35

+0

soapenv:Fault> soapenv:Server.userException org.xml.sax.SAXException:實測值的數組元素內的字符數據,而反序列化 - 名稱 Davey 2011-06-02 08:51:27

+0

@ user78087該錯誤與Serializable無關。 – EJP 2011-06-02 09:00:55

0
 ObjectOutputStream stream = null; 
    try { 
     stream = new ObjectOutputStream(out); 
     String strings[][] = { 
       {"a", "b", "c"}, 
       {"1", "2", "3"}, 
     }; 
     stream.writeObject(strings); 
    } catch (IOException e) { 
     e.printStackTrace(); //$REVIEW$ To change body of catch statement use File | Settings | File Templates. 
    } 

這裏就是答案。數組默認情況下是可序列化的。只需將它像另一個可序列化對象一樣寫入ObjectOutputStream

相關問題