Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java what .read() function returns ? And Java IOException

I have this line of code.And numbers.txt has a string of these numbers : 123456789 .Running it prints : 235689 . Why? What does .read() do ? And when 'while(fin.read() > -1 )' is TRUE? Also about the Exception why i get IOException Error when not using it since the program is correct?

import java.io.*;

public class Read {


    public static void main(String[] args) throws Exception {



        FileReader fin = new FileReader("numbers.txt");

        while(fin.read() > -1 ){

         System.out.print((char) fin.read());
         System.out.print((char) fin.read());

        }
        fin.close(); 


    }

}
like image 554
Konstantinos Korovesis Avatar asked Dec 09 '25 23:12

Konstantinos Korovesis


1 Answers

You are discarding every third character. I suggest storing the character you read and printing that.

for(int ch; (ch = fin.read()) > -1; )
     System.out.print((char) ch);

I suggest you use a BufferedReader instead like this

try(BufferedReader br = new BufferedReader(new FileReader("numbers.txt"))) {
    for(String line; (line = br.readLine()) != null; )
        System.out.println(line);
} // closes the br
like image 131
Peter Lawrey Avatar answered Dec 12 '25 12:12

Peter Lawrey