devxlogo

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.writeInt(10);oos.writeObject(new Integer(5));oos.close();

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() );ois.close();

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.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Engineering Leaders Spot Weak Proposals

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.