Program for reading bytes from file using FileInputStream (Byte Stream)
In Java, FileInputStream is a bytes stream class that’s used to read bytes from file. The following program will use FileInputStream to read a file named 'test.txt' and display its content to console. The FileInputStream class is present in java.io package.
To read the contents from a file you have to follow below stpes:
To read the contents from a file you have to follow below stpes:
- Create an object of FileInputStream by passing filename in constructor call. This statement throws FileNotFoundException so you have to surround this statement with try-catch block.
- To read bytes from stream use, int read( ) method of FileInputStream class. This method reads a byte from stream. This method returns next byte of data from file or -1 if the end of the file is reached. Read method throws IOException in case of any IO errors.
- To close the FileInputStream, use void close( ) method of FileInputStream class. This also throws IOException.
The following program will the read the contents from file which is passed from command line by use. The contents in file 'test.txt' are:
PROGRAM
Hi
This is printing from
file 'text.txt'.
PROGRAM
import java.io.*;
class ReadBytes
{
public static void main (String[] args)
{
FileInputStream inFile=null;
int b;
try
{
inFile = new FileInputStream(args[0]);
while((b=inFile.read())!=-1)
{
System.out.print((char)b);
}
inFile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
OUTPUT
C:\>javac ReadBytes.java C:\>java ReadBytes test.txt Hi This is printing from file 'text.txt'.