Java writing objects to file

Java Guides

We can also write String, Arrays, Integer, and date to file using ObjectOutputStream class because these classes internally implement a java.io.Serializable interface.

2. Write an Object to File Example

class Employee implements Serializable < private static final long serialVersionUID = 1L; private int id; private String name; public int getId() < return id; > public void setId(int id) < this.id = id; > public String getName() < return name; > public void setName(String name) < this.name = name; > >

Let’s create an employees.txt file under some directory. Write code to write employee object to file employees.txt.

/** * This Java program demonstrates how to write object in file. * @author javaguides.net */ public class ObjectOutputStreamExample < public static void main(String[] args) < final Employee employee = new Employee(); employee.setId(100); employee.setName("ramesh"); try (final FileOutputStream fout = new FileOutputStream("employees.txt"); final ObjectOutputStream out = new ObjectOutputStream(fout)) < out.writeObject(employee); out.flush(); System.out.println("success"); > catch (IOException e) < e.printStackTrace(); > > >

Источник

How to write an Object to a File in Java

In this quick article, you’ll learn how to write a Java Object to a file in the local file system. To do this serialization, the class of the object must implement the Serializable interface. This will enable us to perform basic I/O operations on the class in Java.

To write an object to a file, all you need to do is the following:

  • Create a Java class that implements the Serializable interface.
  • Open a new or an existing file using FileOutputStream .
  • Create an instance of ObjectOutputStream and pass FileOutputStream as an argument to its constructor.
  • Use ObjectOutputStream.writeObject() method to write the object to the file.
public class User implements Serializable  public String name; public String email; private String[] roles; private boolean admin; public User()  > public User(String name, String email, String[] roles, boolean admin)  this.name = name; this.email = email; this.roles = roles; this.admin = admin; > // getters and setters, toString() . (omitted for brevity) > 

The following example demonstrates how you can create a User object and write it to a file in Java 7 or higher:

try (FileOutputStream fos = new FileOutputStream("object.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos))  // create a new user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // write object to file oos.writeObject(user); > catch (IOException ex)  ex.printStackTrace(); > 

In older Java versions (Java 6 or below), you have to manually close ObjectOutputStream as shown below:

try  FileOutputStream fos = new FileOutputStream("object.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); // create a new user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // write object to file oos.writeObject(user); // close writer oos.close(); > catch (IOException ex)  ex.printStackTrace(); > 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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.

Источник

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

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

Источник

Читайте также:  Схема сварочного полуавтомата питон пдг 20
Оцените статью