Java saving object to file

How to Write an Object to File in Java

On this tutorial we are going to see how you can store an object to a File in your File system in Java. Basically to perform basic IO operations on object, the class of the object has to implement the Serializable interface. This gives the basic interface to work with IO mechanisms in Java. In short, in order to write an object to a file one should follow these steps:

  • Create a class that implements the Serializable interface.
  • Open or create a new file using FileOutputStream .
  • Create an ObjectOutputStream giving the above FileOutputStream as an argument to the constructor.
  • Use ObjectOutputStream.writeObject method to write the object you want to the file.

Let’s take a look at the code snippets that follow:

package com.javacodegeeks.java.core; import java.io.Serializable; public class Student implements Serializable < //default serialVersion id private static final long serialVersionUID = 1L; private String first_name; private String last_name; private int age; public Student(String fname, String lname, int age)< this.first_name = fname; this.last_name = lname; this.age = age; >public void setFirstName(String fname) < this.first_name = fname; >public String getFirstName() < return this.first_name; >public void setLastName(String lname) < this.first_name = lname; >public String getLastName() < return this.last_name; >public void setAge(int age) < this.age = age; >public int getAge() < return this.age; >@Override public String toString() < return new StringBuffer(" First Name: ").append(this.first_name) .append(" Last Name : ").append(this.last_name).append(" Age : ").append(this.age).toString(); >>
package com.javacodegeeks.java.core; import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class ObjectIOExample < private static final String filepath="C:\\Users\\nikos7\\Desktop\\obj"; public static void main(String args[]) < ObjectIOExample objectIO = new ObjectIOExample(); Student student = new Student("John","Frost",22); objectIO.WriteObjectToFile(student); >public void WriteObjectToFile(Object serObj) < try < FileOutputStream fileOut = new FileOutputStream(filepath); ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); objectOut.writeObject(serObj); objectOut.close(); System.out.println("The Object was succesfully written to a file"); >catch (Exception ex) < ex.printStackTrace(); >> >
The Object was succesfully written to a file

This was an example on how to write an Object to a File in Java.

Читайте также:  Css flex right to left

Источник

ObjectOutputStream in Java — write Object to File

ObjectOutputStream in Java - write Object to File

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

ObjectOutputStream in Java can be used to convert an object to OutputStream. The process of converting object to stream is called serialization in java. Once an object is converted to Output Stream, it can be saved to file or database, send over the network or used in socket connections. So we can use FileOutputStream to write Object to file.

ObjectOutputStream

ObjectOutputStream is part of Java IO classes and its whole purpose is to provide us a way to convert java object to a stream. When we create an instance of ObjectOutputStream, we have to provide the OutputStream to be used. This OutputStream is further used by ObjectOutputStream to channel the object stream to underlying output stream, for example, FileOutputStream.

ObjectOutputStream requirement

The object that we want to serialize should implement java.io.Serializable interface. Serializable is just a marker interface and doesn’t have any abstract method that we have to implement. We will get java.io.NotSerializableException if the class doesn’t implement Serializable interface. Something like below exception stack trace.

java.io.NotSerializableException: com.journaldev.files.EmployeeObject at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at com.journaldev.files.ObjectOutputStreamExample.main(ObjectOutputStreamExample.java:21) 

Java ObjectOutputStream Example to write object to file

Le,t’s look at java ObjectOutputStream example to write an object to file. For that first of all, we should have a class with some properties. Let’s create an Object that we will save into the file.

package com.journaldev.files; import java.io.Serializable; public class Employee implements Serializable < private static final long serialVersionUID = -299482035708790407L; private String name; private String gender; private int age; private String role; // private transient String role; public Employee(String n) < this.name = n; >public String getGender() < return gender; >public void setGender(String gender) < this.gender = gender; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >public String getRole() < return role; >public void setRole(String role) < this.role = role; >@Override public String toString() < return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + " Role=" + this.role; >> 

Notice that it’s not a requirement to have getter/setter for all the properties. Or to have a no-argument constructor. As you can see that above Employee object doesn’t have getter/setter methods for “name” property. It also doesn’t have a no-argument constructor. Here is the program showing how to write Object to file in java using ObjectOutputStream.

package com.journaldev.files; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class ObjectOutputStreamExample < public static void main(String[] args) < Employee emp = new Employee("Pankaj"); emp.setAge(35); emp.setGender("Male"); emp.setRole("CEO"); System.out.println(emp); try < FileOutputStream fos = new FileOutputStream("EmployeeObject.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); // write object to file oos.writeObject(emp); System.out.println("Done"); // closing resources oos.close(); fos.close(); >catch (IOException e) < e.printStackTrace(); >> > 

java ObjectOutputStream example to write object to file

Below image shows the output of the above program. If you are wondering what is the content of EmployeeObject.ser file, it’s a bit garbled and something like below.

��srcom.journaldev.files.Employee�����yyIageLgendertLjava/lang/String;Lnameq~Lroleq~xp#tMaletPankajtCEO 

ObjectOutputStream with a transient

If we don’t want some object property to be converted to stream, we have to use the transient keyword for that. For example, just change the role property like below and it will not be saved.

private transient String role; 

ObjectOutputStream and serialVersionUID

Did you noticed the serialVersionUID defined in the Employee object? It’s used by ObjectOutputStream and ObjectInputStream classes for write and read object operations. Although it’s not mandatory to have this field, but you should keep it. Otherwise anytime you change your class that don’t have effect on earlier serialized objects, it will start failing. For a detailed analysis, go over to Serialization in Java. If you are wondering whether our program worked fine or not, use below code to read an object from the saved file.

FileInputStream is = new FileInputStream("EmployeeObject.ser"); ObjectInputStream ois = new ObjectInputStream(is); Employee emp = (Employee) ois.readObject(); ois.close(); is.close(); System.out.println(emp.toString()); //Output will be "Employee:: Name=Pankaj Age=35 Gender=Male Role=CEO" 

That’s all about java ObjectOutputStream and how to use it to write the object to file. You can checkout more Java IO examples from our GitHub Repository. Reference: API Doc

Читайте также:  Php http post requests

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью