[java] FileInputStream and Reading line by line:

The computer that we are using right now is digital electronic, it is digital because all the information inside it is represented by streams of numbers, more specifically binary numbers. From the perspective of Computer every single file is nothing but a stream of binary numbers. Still now sometimes i stare at my computer and think what not we are making it to do so but it knows nothing more than 0 and 1?  WTF! (Well, That’s Fantastic!)

Before dealing with FileInputStream first of all we have to know what FileInputStream really is.

FileInputIstream is basically a child class of InputStream. It obtains input bytes from a file in a file system. Stream classes basically deal with binary datas and in binary there is no such thing as a “line” so FileInputStream does not have any method which is related with lines.

Our objective is to read from a file line by line using FileInputStream.

First of all it’s in a different not included in java.lang package so if we will use FileInputStream we need to import java.io.* at the beginning of the class.

Scanner or BufferedReader has methods to work with lines so if we can can somehow scan/read Streams through Scanneror BufferedReader, then we can read them line by line using nextLine() or readLine() method.

Constructor Summary of Scanner
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
more…

Scanner does give us opportunity to pass a InputStream through its constructor.

Now, we need to think of a way to make an connection our given file and java.

Constructor of  FileInputStream 
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

 throws FileNotFoundException
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

throws FileNotFoundException

From the summary of the constructor of FileInputStream, we can easily guess  at least two way to make this linkage through the constractor:

1. FileInputStream(String name)
2. FileInputStream(File file)

1. FileInputStream(String name): i think this is the most straight forward way to do this thing. If the file we want to read and our file which we want to to read line by line are at the same directory then we can just write that files name and extension as name constractor and as this constractor throws FileNotFoundException so we also need to handle that exception.

Example: if we want to read a file named “sample.txt” then we would write:

try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
}
catch (FileNotFoundException e){
System.out.println(e);

But if file which we want to to read line by line are not at the same directory then we have to write that files directory briefly and we have to use double ‘//’ in place of single ‘/’ (FYI: as ‘/’ is a escape character and you can’t store a single ‘/’ in a character veritable). Example: if we want to read a file named “sample.txt” which is located at the directory of “C:\Documents and Settings\User\Desktop\sample.txt”, then you have to write:

FileInputStream fileInStreamObj = new FileInputStream("C:\\Documents and Settings\\User\\Desktop\\sample.txt" );

try blocks confines the scope of variables, so we can put this previous piece of code inside same try  block.

Combinig all the pieces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
InputStream inStreamObject = ((InputStream) fileInStreamObj);
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

2. FileInputStream(File file): If we want to use this contractor, first of all we need to define file location with an object of File and then let it go through with FileInputStreams constractor and this constractor also throws FileNotFoundException so we also need to handle that exception.:

try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
}
catch (FileNotFoundException e){
System.out.println(e);
}

Now we need to convert this FileInputStream into InputStream, but they are  in the same tree so we can cast them. So here we go:


InputStream inStreamObject = (InputStream) fileInStreamObj
Scanner sc = new Scanner(  inStreamObject );
String input = sc.nextLine();

combining all peaces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
InputStream inStreamObject = (InputStream) fileInStreamObj;
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}



we can also do similar thing using BufferedReader:

Constructor Summary of BufferedReader
BufferedReader(Reader in)
Create a buffering character-input stream that uses a default-sized input buffer.
more…

So BufferedReader can take Reader as constructor.

Now we have to convert FileInputStream into Reader or any of its child class.

Constructor Summary of InputStreamReader extends Reader
InputStreamReader(InputStream in)
Create an InputStreamReader that uses the default charset.
more…

InputStreamReader can take  FileInputStream and its in the the same tree of Reader so we can cast any InputStreamReader object into Reader.
ReadLine() method of BufferedReader throws IOException, so we also need to handle that exception.
so,
try{
InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
}
catch(IOException e){
System.out.println(e);
}

combinig previous pieces:

import java.io.*;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt");
try{InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
System.out.println(input);
}
catch(IOException e){
System.out.println(e);
}
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

Hurrah, now we know how to read a line using FileInputStream. Now using a loop until Scanner hasNext()  or BufferedReader’s readLine() method returns a null!