Search code examples
javafile-iojava-iofileinputstream

Using FileInputStream to read text from file


I have a text file with the contents abcdefgh saved on my computer. I wanted to use FileInputStream to display the characters on my console while also measuring the time it took to do so. It looks like this:

public class Readtime {
    public static void main(String args[]) throws Exception{
        FileInputStream in=new FileInputStream("bolbol.txt");
        while(in.read()!=-1){
            long startTime = System.nanoTime();
            int x = in.read();
            long endtime = System.nanoTime();
            System.out.println(endtime-startTime);
            System.out.println((char)x);
        }
        in.close();
    }
}

What I get on the console is the following:

8863
b
7464
d
6998
f
6997
h

Now where are the rest of the letters? It's as if only 4 read operations were done. My mind is going in the direction of char size and that read() only reads a single byte at a time but I'm not getting anywhere.


Solution

  • while(in.read()!=-1){
        long startTime =  System.nanoTime();
        int x=in.read();
    

    You are reading the data in while condition and printing in the loop again reading

    int i=0;  
    while((i=in.read())!=-1){  
        System.out.println((char)i);  
    }  
    

    You can check the official documentation here