[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!

3 thoughts on “[java] FileInputStream and Reading line by line:

  1. Pingback: Fileinputstream read | Fotolamp

  2. usman ahmed

    aoa,
    sadaf h r u,
    can u plz tell me how to read file line by line for e.g we have file and the data written in it is that
    Q: what is your nationality?
    Ans: your nationality is…..
    Q: what is your name?
    Ans: your name is…….
    Q: what is your fav color?
    Ans: your fav color is……

    i want that the questions in odd and ans in even lines so i want to output them in even and odd form like all ans in even and all question in odd how can i do this??? reply me as soon as possible

    1. Well, you can just store Strings returned from nextLInes and store them on a Array or preferably on a linked list by, first one as odd, and second one as even, and continue the process until it has at least one (hasNex() ).

      Hopefully this code will help::::

      import java.io.File;
      import java.io.FileNotFoundException;
      import java.util.LinkedList;
      import java.util.Scanner;

      public class CopyOffile {
      public static void main(String [] args) throws FileNotFoundException{
      String dir=”C:\\Users\\User\\workspace\\text.txt”; // enter your directory, and dont forget to use double slash(//) instead of single slash (/)

      LinkedList oddList= new LinkedList();
      LinkedList evenList= new LinkedList();

      File file = new File(dir);
      Scanner sc= new Scanner(file);

      while (sc.hasNextLine()){
      oddList.add(sc.nextLine());
      if(sc.hasNextLine()){
      evenList.add(sc.nextLine());
      }
      }

      while(!oddList.isEmpty()){
      System.out.println( oddList.pop());
      }
      while(!evenList.isEmpty()){
      System.out.println( evenList.pop() );
      }

      }
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s