The readChar() method of DataInputStream class in Java is used to read two input bytes and returns a char value. This method basically reads the bytes as character that are written by writechar() method of DataOutputStream class.
Syntax:
Java
Program 2: Assume the existence of file "demo.txt".
Java
public final char readChar()
throws IOException
Specified By: This method is specified by readChar() method of DataInput interface.
Parameters: This method does not accept any parameter.
Return value: This method returns the char value interpreted by the two bytes of input stream.
Exceptions:
- EOFException - It throws EOFException if the input stream is ended before two bytes can be read.
- IOException - This method throws IOException if the stream is closed or some other I/O error occurs.
// Java program to illustrate
// DataInputStream readChar() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Create byte array
byte[] buf = { 71, 69, 69, 75, 83 };
// Create file output stream
FileOutputStream outputStream
= new FileOutputStream("c:\\demo.txt");
// Create data output stream
DataOutputStream dataOutputStr
= new DataOutputStream(outputStream);
for (byte b : buf) {
// Write character to
// the dataOutputStream
dataOutputStr.writeChar(b);
}
dataOutputStr.flush();
// Create file input stream
FileInputStream inputStream
= new FileInputStream("c:\\demo.txt");
// Create data input stream
DataInputStream dataInputStr
= new DataInputStream(inputStream);
while (dataInputStr.available() > 0) {
// Print character
System.out.print(
dataInputStr.readChar());
}
}
}
// Java program to illustrate
// DataInputStream readChar() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Create byte array
byte[] buf = { 71, 69, 69, 75, 83,
70, 79, 82, 71, 69,
69, 75, 83 };
// Create file output stream
FileOutputStream outputStream
= new FileOutputStream("c:\\demo.txt");
// Create data output stream
DataOutputStream dataOutputStr
= new DataOutputStream(outputStream);
for (byte b : buf) {
// Write character to
// the dataOutputStream
dataOutputStr.writeChar(b);
}
dataOutputStr.flush();
// Create file input stream
FileInputStream inputStream
= new FileInputStream("c:\\demo.txt");
// Create data input stream
DataInputStream dataInputStr
= new DataInputStream(inputStream);
while (dataInputStr.available() > 0) {
// Print character
System.out.print(
dataInputStr.readChar());
}
}
}

