/*
Read char from file using DataInputStream
This Java example shows how to read a Java char primitive value from file using
readChar method of Java DataInputStream class.
*/
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadCharFromFile {
public static void main(String[] args) {
String strFilePath = "C://FileIO//readChar.txt";
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
/*
* To create DataInputStream object, use
* DataInputStream(InputStream in) constructor.
*/
DataInputStream din = new DataInputStream(fin);
/*
* To read a Java character primitive from file, use
* byte readChar() method of Java DataInputStream class.
*
* This method reads 2 bytes and returns unicode char value(Unicode char
* occupies 2 bytes).
*/
char ch = din.readChar();
System.out.println("Char : " + ch);
/*
* To close DataInputStream, use
* void close() method.
*/
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}
Bookmark/Search this post with:
This program doesn't work
This program doesn't work
this program is not working correct it
this program is not working correct it
It Works
You need to have the mentioned readChar.txt file in the proper location. Otherwise it throws FileNotFoundException.
In addition, It returns Unicode char, so it might display as ? in the console.
Post new comment