Signup/Sign In

Java DataInputStream readChar() Method

In this tutorial, we will learn about the readChar() method of DataInputStream class in Java. This method is used to read two input bytes ( i.e. 16-bits) and returns a character value. It reads the bytes as char that is written by the writechar() method of the DataOutputStream class.

Syntax

This is the syntax of this method. It does not accept any parameter and returns the signed char value interpreted by the two bytes of the current input stream.

public final char readChar() throws IOException

Example: Read char using ReadChar() Method

In this example, we are implementing the readChar() method to read the 16-bits data at a time from the file, firstly we check if the pointer of the stream is at the correct position and did not reach the end of the file. Here, we read the data from the file and print on the console, for the reference the data inside the file is given after the output of this program.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		FileInputStream inputStream  = new FileInputStream("E:\\studytonight\\output.txt"); 
		DataInputStream dataInputStream = new DataInputStream(inputStream); 
		while(dataInputStream.available()>0)
		{	           
            System.out.print(" "+dataInputStream.readChar());  
        }  
	}  
}


A B C D E F

output.txt
A B C D E F

Example: EOFException in ReadChar() Method

Here, we are facing an exception thrown when we reach the end of the file while reading the file. It throws an exception called End Of The File Exception EOFException.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		FileInputStream inputStream  = new FileInputStream("E:\\studytonight\\output.txt"); 

		DataInputStream dataInputStream = new DataInputStream(inputStream); 

		System.out.print(" "+dataInputStream.readChar());          
	}  
}


Exception in thread "main" java.io.EOFException
at java.base/java.io.DataInputStream.readChar(DataInputStream.java:369)
at studytonight.StudyTonight.main(StudyTonight.java:16)

Conclusion

In this tutorial, we learned about the readChar() method of DataInputStream class in Java which reads the two input bytes, and returns a char value, written by the writechar() method of DataOutputStream class, of the current input stream.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.