Java.io.ObjectOutputStream.writeUTF() Method



Description

The java.io.ObjectOutputStream.writeUTF(String str) method writes primitive data write of this String in modified UTF-8 format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream.

Declaration

Following is the declaration for java.io.ObjectOutputStream.writeUTF() method.

public void writeUTF(String str)

Parameters

str − The String to be written

Return Value

This method does not return a value.

Exception

IOException − If I/O errors occur while writing to the underlying stream

Example

The following example shows the usage of java.io.ObjectOutputStream.writeUTF() method.

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {      String s = "Hello World!";
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUTF(s);
         oout.writeUTF("Bye world!");

         // close the stream
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois =
                 new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print what we wrote before
         System.out.println("" + ois.readUTF());
         System.out.println("" + ois.readUTF());


      } catch (Exception ex) {
         ex.printStackTrace();
      }

   }
}

Let us compile and run the above program, this will produce the following result −

Hello World!
Bye world!

Advertisements