[ACCEPTED]-Java serialization of multidimensional array-vector
Accepted answer
Arrays in Java are serializable - thus Arrays 5 of Arrays are serializable too.
The objects 4 they contain may not be, though, so check 3 that the array's content is serializable 2 - if not, make it so.
Here's an example, using 1 arrays of ints.
public static void main(String[] args) {
int[][] twoD = new int[][] { new int[] { 1, 2 },
new int[] { 3, 4 } };
int[][] newTwoD = null; // will deserialize to this
System.out.println("Before serialization");
for (int[] arr : twoD) {
for (int val : arr) {
System.out.println(val);
}
}
try {
FileOutputStream fos = new FileOutputStream("test.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(twoD);
FileInputStream fis = new FileInputStream("test.dat");
ObjectInputStream iis = new ObjectInputStream(fis);
newTwoD = (int[][]) iis.readObject();
} catch (Exception e) {
}
System.out.println("After serialization");
for (int[] arr : newTwoD) {
for (int val : arr) {
System.out.println(val);
}
}
}
Output:
Before serialization
1
2
3
4
After serialization
1
2
3
4
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.