How To Read File In Java

In this section we will discuss about about how data of a file can be read in Java.

How To Read File In Java

In this section we will discuss about about how data of a file can be read in
Java.

A file can contain data as bytes, characters, binary data etc. To read a
file in Java we can use following of the classes :

for reading byte/s data

FileInputStream

for reading character/s data

FileReader

FileInputStream reads the raw bytes stream and FileReader reads the character
streams. To read data from the file we can use the read() method defined by the
classes itself or inherited from their parent class.

Example

This example demonstrates that how to read a file in java. To read a file
there must be a file which contents can be read so, I have created a file named
test.txt, contains some data, in the current directory. Then I have created a
Java Program to read the data of a file and used the FileInputStream
class of java.io package. To read the file contents used read() method of the
FileInputStream.