Java - DataOutputStream writeChars(String s) method



Description

The Java DataOutputStream writeChars(String s) method writes a character sequence to the stream.

Declaration

Following is the declaration for java.io.DataOutputStream.writeChars(String s) method −

public final void writeChars(String s)

Parameters

s − a string value to be written to the underlying output stream.

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Example - Usage of DataOutputStream writeChars(String s) method

The following example shows the usage of Java DataOutputStream writeChars(String s) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A String is initialized with some text. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before.

We've written the string to stream using writeChars() method. As next step, stream is flushed. As next step, we've created a FileInputStream object based on file written earlier. Then DataInputStream is initialized with FileInputStream object created. Now dataInputStream is iterated to print the contents. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

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

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);
         
         // write string to the dos
         dos.writeChars(buf);
         
         // 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) {
         
            // read character
            char c = dis.readChar();
            
            // print
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if an 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 writeChars(String s) method

The following example shows the usage of Java DataOutputStream writeChars(String s) method. We've created InputStream, DataInputStream, FileOutputStream and DataOutputStream reference. A String is initialized with some text. A FileOutputStream object is created. Then DataOutputStream is initialized with FileOutputStream object created before.As a special case, we're closing the stream before writing any value to check if it supports writing values after closing it.

We've written the string to stream using writeChars() method. As next step, stream is flushed. As next step, we've created a FileInputStream object based on file written earlier. Then DataInputStream is initialized with FileInputStream object created. Now dataInputStream is iterated to print the contents. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

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

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 stream
         dos.close();         
         
         // write string to the dos
         dos.writeChars(buf);
         
         // 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) {
         
            // read character
            char c = dis.readChar();
            
            // print
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if an 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.writeChars(DataOutputStream.java:299)
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:29)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.InputStream.close()" because "is" is null
	at com.tutorialspoint.DataOutputStreamDemo.main(DataOutputStreamDemo.java:58)

Example - Writing and Reading a String Using writeChars(String s)

The following example shows the usage of Java DataOutputStream writeChars(String s) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

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

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try {
         // Create a DataOutputStream to write to a file
         FileOutputStream fileOutput = new FileOutputStream("output.dat");
         DataOutputStream dataOutput = new DataOutputStream(fileOutput);

         // String to write
         String message = "Hello,World!"; 

         // Write the string as characters (2 bytes per character)
         dataOutput.writeChars(message);

         // Close the output stream
         dataOutput.close();
         System.out.println("String successfully written to output.dat");

         // Read the string back
         FileInputStream fileInput = new FileInputStream("output.dat");
         DataInputStream dataInput = new DataInputStream(fileInput);

         // Read and reconstruct the string character by character
         StringBuilder readMessage = new StringBuilder();
         while (fileInput.available() > 0) {
            readMessage.append(dataInput.readChar()); // Read two bytes per character
         }

         // Print the reconstructed string
         System.out.println("String read from file: " + readMessage);

         // Close the input stream
         dataInput.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

String successfully written to output.dat
String read from file: Hello, World!

Explanation

Writing a String as Bytes

  • writeChars("Hello, World!") writes each character as two bytes.

  • ASCII characters (H, e, l, l, o, , etc.) are stored as two bytes each.

Reading the String

  • Since writeChars() does not store length, we must read character-by-character using readChar().

  • The loop reads two bytes at a time and reconstructs the string.

java_io_dataoutputstream.htm
Advertisements