Serializing Arrays
9 November 2007We already know that we can serialize object of classes that implement serializable interface. Make a class that implements serializable interface, make an object of it and save it to disk. You may retrieve to confirm that the object has the required data or not. Vector class also implements serializable interface, so you can also store vectors on disk.
How about Arrays?
Arrays are of some type. Thing to note is which classes implement Serializable interface. Integer, Short, Float, Double, Long, String classes implement Serializable interface. So arrays of these types can be serialized.
Lets take an example:
int[] array = new int [5]; array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; int[] tmp_array = new int [5]; // writing array to disk FileOutputStream f_out = new FileOutputStream("C:\\myarray.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (array); // reading array from disk FileInputStream f_in = new FileInputStream("C:\\myarray.data"); ObjectInputStream obj_in = new ObjectInputStream (f_in); tmp_array = (int[])obj_in.readObject(); for(int i=0;i<5;i++) System.out.println(tmp_array[i]);
In the example above, we declared an integer array and inserted some data into it. Then that array was written to disk (serialized) on a file.
To make sure that the array was saved with data, we fetched the array from the same file using FileInputStream and ObjectInputStream. At the end, the fetched array is displayed on the console and now we are sure that we achieved what we wanted.
Output:
10 20 30 40 50
Similarly we can also searilize Integer, Short, Float, Double, Long, String.
int a= 10; // writing int to disk FileOutputStream f_out = new FileOutputStream("C:\\myint.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (a);
Happy coding.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Serializing Arrays