这可能是一个愚蠢的问题,但我想将2维字符串数组转换为java中的可序列化对象。这样做的最佳方式是什么?
答案 0 :(得分:7)
数组已经是Serializable。 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();
}
}
<强>资源:强>
答案 1 :(得分: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,就像另一个可序列化对象
一样