- Convert object to stream java
- Nested Class Summary
- Field Summary
- Fields inherited from interface java.io.ObjectStreamConstants
- Constructor Summary
- ObjectOutputStream in Java — write Object to File
- ObjectOutputStream
- ObjectOutputStream requirement
- Java ObjectOutputStream Example to write object to file
- ObjectOutputStream with a transient
- ObjectOutputStream and serialVersionUID
- Convert one/ heterogeneous object into another – stream lambda (java8 /example)
- Program – convert /translate one object into another(lambda stream java8)
- Output – convert /translate one object into another (lambda stream java8)
- You may also like:
Convert object to stream java
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconstituted on another host or in another process. Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object’s fields and arrays, and the closure of any other objects referenced from the initial objects. The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written. Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method. The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. For example to write an object that can be read by the example in ObjectInputStream:
FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeInt(12345); oos.writeObject("Today"); oos.writeObject(new Date()); oos.close();
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void writeObject(java.io.ObjectOutputStream stream) throws IOException private void readObjectNoData() throws ObjectStreamException;
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object’s superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput. Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state. Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object’s serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs. Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To serialize an enum constant, ObjectOutputStream writes the string returned by the constant’s name method. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored—all enum types have a fixed serialVersionUID of 0L. Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.
Nested Class Summary
Field Summary
Fields inherited from interface java.io.ObjectStreamConstants
Constructor Summary
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(); >> >
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
Convert one/ heterogeneous object into another – stream lambda (java8 /example)
Program – convert /translate one object into another(lambda stream java8)
We would like to convert DBAddress/DBUser objects to corresponding Address/User objects respectively.
In main method, we are performing following operations.
- We will call getDBUserList to simulate database operation.
- DBUsers class composes DBAddress class.
- We will simulate object retrieval operation from database.
- We will print the attributes of DBUser and DBAddress objects.
- We will use lambda stream (java8) to convert heterogeneous objects.
- Convert DBAddress object to Address object.
- Convert DBUser object to User Object.
package org.learn; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /****** Database clases ********/ class DBAddress < public String street; public String locality; public String area; public String pinCode; public DBAddress(String street, String locality,String area, String pinCode) < this.street = street; this.locality = locality; this.area = area; this.pinCode = pinCode; >public String toString() < return street + " " + locality + " " + area + " " + pinCode; >> class DBUser < public String firstName; public String lastName; public String age; public DBAddress address; public String contact; public String role; public DBUser(String firstName, String lastName, String age, DBAddress address, String contact, String role) < this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address; this.contact = contact; this.role = role; >public String toString() < return "[DbUser: " + firstName + " " + lastName + " [address: " + address.toString() + "] " + contact + " " + role + "]"; >> /************ Domain Classes ****************************/ class Address < public String street; public String locality; public String area; public String pinCode; public Address(String street, String locality,String area, String pinCode) < this.street = street; this.locality = locality; this.area = area; this.pinCode = pinCode; >public String toString() < return " " + street + " " + locality + " " + area + " " + pinCode; >> class User < public String name; public String age; public Address address; public String contact; public User(String name, String age, Address address, String contact) < this.name = name; this.age = age; this.address = address; this.contact = contact; >public String toString() < return "[User: " + name + " " + age + " " + " [address: " + address.toString() + "] " + contact + "]"; >> /*****************************************************/ public class ObjectTranslator < // Suppose we are getting this from database private static List getDBUserList() < List dbUserList = new ArrayList(); // First user DBAddress dbAddress1 = new DBAddress ("Street hw", "Windsor", "Windsor", "112211"); DBUser dbUser1 = new DBUser ("Mike", "Cook", "55", dbAddress1, "001225365", "ViewOnly"); dbUserList.add(dbUser1); // Second user DBAddress dbAddress2 = new DBAddress ("Street sw", "Hudson park", "Hudson", "221102"); DBUser dbUser2 = new DBUser ("Peter", "thomas", "41", dbAddress2, "003665412", "Admin"); dbUserList.add(dbUser2); return dbUserList; >public static void main(String[] args) < List dbUserList = getDBUserList(); dbUserList.forEach(db ->System.out.println(db)); List userList = dbUserList.stream().map(db -> < DBAddress dbAddress = db.address; Address address = new Address(dbAddress.street, dbAddress.locality, dbAddress.area, dbAddress.pinCode); User user = new User(db.firstName, db.age, address, db.contact); return user; >).collect(Collectors.toList()); System.out.println("\nObject translated DBUser to User : "); userList.forEach(user -> System.out.println(user)); > >
Output – convert /translate one object into another (lambda stream java8)
[DbUser: Mike Cook [address: Street hw Windsor Windsor 112211] 001225365 ViewOnly] [DbUser: Peter thomas [address: Street sw Hudson park Hudson 221102] 003665412 Admin] Object translated DBUser to User : [User: Mike 55 [address: Street hw Windsor Windsor 112211] 001225365] [User: Peter 41 [address: Street sw Hudson park Hudson 221102] 003665412]
You may also like: