Skip to content
Advertisement

How to solve infinite readLine while

I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.

I don’t know what to do to try to solve it.

private int sizeOfFile (File txt) {
    FileReader input = null;
    BufferedReader count = null;
    int result = 0;
    try {
        
        input = new FileReader(txt);
        count = new BufferedReader(input);
        
        while(count != null){
        String line = count.readLine();
            System.out.println(line);
        result++;
        }
        
    } catch (FileNotFoundException ex) {
       ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            input.close();
            count.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    return result;
}

It has to stop when it detects a null, which means there are no more lines, but it keeps going.

Advertisement

Answer

When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:

count = new BufferedReader(input); //count is holding an instance of BufferedReader.

while(count != null){ //here count is non-null and while loop is infinite and program never exits.

Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:

input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
        System.out.println(line);
        result++;
 }

If you are using JDK-1.8 you can shorten your code using the Files API:

int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
      //either print the lines or take the count.
      //stream.forEach(System.out::println); 
      result = (int)stream.count(); 
} catch (IOException e) {
      e.printStackTrace();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement