ObjectInputStream readUTF() Method in Java

In this tutorial, we will learn about ObjectInputStream readUTF() method in Java.

Java ObjectInputStream readUTF()

An ObjectInputStream deserializes previously written objects and primitive data using ObjectOutputStream.In other words, it is used to recover the already serialized objects. ObjectInputStream helps to ensure all objects created in classes are same as that present in Java Virtual Machine. The primitive data supporting java.io.Serializable or java.io.Externalizable interface can only be read from ObjectInputStream. Classes are loaded using standard mechanisms

>>>Why do we use ObjectInputStream readUTF() Method in Java ??

… We use readUTF() method to read a string in UTF-8 format.

Declaration

public String readUTF()

This method requires no parameters.

Return Value

Returns string.

Exception

  • IOException − I/O errors occurring while reading InputStream generates this error.
  • UTFDataFormatException – If InputString is in invalid UTF-8 format encoding.

Program

import java.io.*;
public class DemoObjectInputStream {
//This class creates a new file, and perform write and read using ObjectInputStream .
   public static void main(String[] args) {
      String a = "Welcome ,This is my demo code!";
      
      try {
         FileOutputStream out = new FileOutputStream("demo.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         oout.writeUTF(a);
         oout.writeUTF("Great Work");
         oout.flush();
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("demo.txt"));

         System.out.println("" + ois.readUTF());
         System.out.println("" + ois.readUTF());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

OUTPUT:

Welcome ,This is my demo code! 
Great Work

You may also refer to:

 

Leave a Reply

Your email address will not be published. Required fields are marked *