Using FileInputStream to read text from file

2.9k views Asked by At

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.

4

There are 4 answers

0
RaceBase On BEST ANSWER
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

0
Raman Shrivastava On

Change

while(in.read()!=-1){  

to

int x;
while((x=in.read())!=-1){  

and delete

int x=in.read();

You were reading twice.. and printing alternate time.. that's why characters missing

1
Sumit Gupta On

each time in.read(); is called the file's next character is read. So you must read a character once per iteration of loop.

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

If you see your output then you'll see that you have read the alternate characters because you are reading twice in loop, once in while condition and once to print.

0
Ziyad On

You can use this it will help you

public class Readtime {
    public static void main(String args[]) throws Exception{
        FileInputStream in=new FileInputStream("bolbol.txt");

        long startTime = System.nanoTime();

        byte b[]=new byte[in.available()]; 
        fis.read(b);
        String readOnConsole=new String(b);
        System.out.println(readOnConsole);
        long endtime = System.nanoTime();
        System.out.println(endtime-startTime);
        in.close();
    }
}