Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Intermediate
Nov 17, 2004



Application Security Testing: An Integral Part of DevOps

Persist Java Objects in a File and Retrieve Them Later

For persisting Java objects in a file, use java.io.ObjectOutputStream. ObjectOutputStream writes primitive data types or Java objects. Persistent storage can be accomplished by using a file for the stream. Only serializable objects can be persisted:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\sample.txt"));
oos.writeObject(new String("Hello my dear friends"));
oos.writeObject(new Integer(5));
The above code writes a string object first and then a primitive integer. Later still, it writes another Java object, Integer. All this data is written onto the file C:\sample.txt.

To read Integer back, use ObjectInputStream:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\sample.txt"));
System.out.println("First : object : " + ois.readObject() );
System.out.println("Second : int : " + ois.readInt );
System.out.println("Third : Integer : " + ois.readObject() );
Now, you can assign the read values to variables for processing.

One thing to keep in mind is that the order in which the objects will be read back is the same order in which they were written.

Amit Tuli
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date