View RSS Feed

My Java Tips

Serializing Arrays

Rate this Entry
by , 11-10-2011 at 04:08 PM (4718 Views)
We 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:

Java Code:
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.

Java Code:
	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.

Submit "Serializing Arrays" to Facebook Submit "Serializing Arrays" to Digg Submit "Serializing Arrays" to del.icio.us Submit "Serializing Arrays" to StumbleUpon Submit "Serializing Arrays" to Google

Categories
Java SE

Comments