Java - DataOutputStream writeUTF(String str) method



Description

The Java DataOutputStream writeUTF(String str) method writes a string to the underlying output stream using modified UTF-8 encoding.

The writeUTF(String v) method of DataOutputStream writes a modified UTF-8 encoded string to the output stream. It first writes two bytes (16-bit unsigned) to store the length of the string (in bytes), followed by the UTF-8 encoded characters. writeUTF(String v) automatically stores the string length (in bytes) before writing data. Unlike writeBytes(String v), it correctly supports non-ASCII characters.

Declaration

Following is the declaration for java.io.DataOutputStream.writeUTF(String str) method −

public final void writeUTF(String str)

Parameters

str − a string value to be written to the output stream.

Return Value

The method returns the value of the written field.

Exception

IOException − If an I/O error occurs.

Example - Usage of DataOutputStream writeUTF(String str) method

The following example shows the usage of Java DataOutputStream writeUTF(String str) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A string[] buf is initialized with some string values. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before. Then string array is iterated to write string values using writeInt() method to the dataoutputstream.

Once string array is fully written into the stream, we've flushed the stream to store the values in the file. Now using FileInputStream and DataInputStream, we're reading the file written earlier. Now we're checking if DataInputStream object has data using available() method. Then using readUTF() method, we're reading every value as string. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      FileOutputStream fos = null;
      DataOutputStream dos = null;
      String[] dbuf = {"Hello", "World!!"};
      
      try {
         // create file output stream
         fos = new FileOutputStream("test.txt");
         
         // create data output stream
         dos = new DataOutputStream(fos);
         
         // for each string in the buffer
         for (String j:dbuf) {
         
            // write string encoded as modified UTF-8
            dos.writeUTF(j);        
         }
         
         // force bytes to the underlying stream
         dos.flush();
         
         // create file input stream
         is = new FileInputStream("test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // read till end of the stream
         while(dis.available()>0) {
         
            // reads characters encoded with modified UTF-8
            String k = dis.readUTF();
            
            // print
            System.out.print(k+" ");
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dos!=null)
            is.close();
         if(dis!=null)
            dis.close();
         if(fos!=null)
            fos.close();
      }
   }
}

Output

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

Hello World!! 

Example - Usage of DataOutputStream writeUTF(String str) method

The following example shows the usage of Java DataOutputStream writeUTF(String str) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A string[] buf is initialized with some string values. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before. Then string array is iterated to write string values using writeUTF() method to the dataoutputstream.

As a special case, we're closing the stream before writing any value to check if it supports writing values after closing it.

Once string array is fully written into the stream, we've flushed the stream to store the values in the file. Now using FileInputStream and DataInputStream, we're reading the file written earlier. Now we're checking if DataInputStream object has data using available() method. Then using readUTF() method, we're reading every value as string. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      FileOutputStream fos = null;
      DataOutputStream dos = null;
      String[] buf = {"Hello", "World!!"};
      
      try {
         // create file output stream
         fos = new FileOutputStream("test.txt");
         
         // create data output stream
         dos = new DataOutputStream(fos);
         
         // close the streams
         dos.close();
		 
         // for each String in the buffer
         for (String j:buf) {
         
            // write string encoded as modified UTF-8
            dos.writeUTF(j);         
         }
         
         // force Strings to the underlying stream
         dos.flush();
         
         // create file input stream
         is = new FileInputStream("test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // read till end of the stream
         while(dis.available()>0) {
         
            // reads characters encoded with modified UTF-8
            String k = dis.readUTF();
            
            // print
            System.out.print(k+" ");
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dos!=null)
            is.close();
         if(dis!=null)
            dis.close();
         if(fos!=null)
            fos.close();
      }
   }
}

Output

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

java.io.IOException: Stream Closed
	at java.base/java.io.FileOutputStream.writeBytes(Native Method)
	at java.base/java.io.FileOutputStream.write(FileOutputStream.java:367)
	at java.base/java.io.DataOutputStream.write(DataOutputStream.java:115)
	at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:397)
	at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:327)
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:32)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.InputStream.close()" because "is" is null
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:62)

As underlying stream FileOutputStream is not supporting write to stream after closing it, we get exception in program execution.

Example - Usage of DataOutputStream writeUTF(String str) method

The following example shows the usage of Java DataOutputStream writeUTF(String str) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try (FileOutputStream fos = new FileOutputStream("output.dat");
         DataOutputStream dos = new DataOutputStream(fos)) {

         String message = "Hello, UTF!";
         dos.writeUTF(message); // Writes the string in UTF-8 format

         System.out.println("UTF string written successfully.");

         FileInputStream fis = new FileInputStream("output.dat");
         DataInputStream dis = new DataInputStream(fis);

         message = dis.readUTF(); // Reads UTF-8 encoded string
         System.out.println("Read String: " + message);

      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

UTF string written successfully.
Read String: Hello, UTF!

Explanation

  • FileOutputStream− Creates a binary file "output.dat" for writing.

  • DataOutputStream− Wraps FileOutputStream to enable writing primitive data types.

  • writeUTF(String str) Method− First writes 2 bytes indicating the length of the UTF-8 encoded string. Then writes the string in modified UTF-8 format.

Binary Representation (output.dat)

If message = "Hello, UTF!", the file will contain−

First 2 bytes− Length of UTF-8 encoded data.

Remaining bytes− UTF-8 encoded "Hello, UTF!".

Example (Hex representation)

00 0C 48 65 6C 6C 6F 2C 20 55 54 46 21

00 0C − Length of the string (12 bytes)

48 65 6C 6C 6F 2C 20 55 54 46 21 − UTF-8 bytes for "Hello, UTF!"

java_io_dataoutputstream.htm
Advertisements