Search code examples
javafilebufferedreader

File Input reads only last few lines from the input file


It's a simple code to read all the content from a .txt file. Not exactly sure what is the issue. I tried with a different test file and it read just line2 and line4 followed by null. It shouldn't even read null as per the while loop condition.

import java.io.*;
import java.util.*;

public class FileInput {

    public ArrayList<String> readFile() {
        ArrayList<String> content = new ArrayList<>();

        try {
            File file = new File("input.txt");
            BufferedReader br = new BufferedReader(new FileReader(file)); 

            String line = null;

            while (br.readLine() != null) {
                line = br.readLine();
                content.add(line);
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File could not be found. " + e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return content;
    }

    public static void main(String []args) {

        FileInput fi = new FileInput();
        fi.readFile();

    }   

}

input.txt

Dangal / Aamir Khan / Fatima Sana
Sanju / Ranbir Kapoor / Dia Mirza
PK / Aamir Khan / Anushka Sharma
Munna Bhai MBBS / Sanjay Dutt / Arshad Warsi
Zindagi Na Milegi Dobara / Farhan Akhtar / Katrina Kaif

output:

Sanju / Ranbir Kapoor / Dia Mirza
Munna Bhai MBBS / Sanjay Dutt / Arshad Warsi
null

Am I doing anything incorrectly or did I make a small mistake somewhere?


Solution

  • You are calling br.readLine() twice which is causing you to skip a few lines while reading the file within the while-loop.

    Change your while to as follows :-

    while ((line = br.readLine()) != null) {
       content.add(line);
       System.out.println(line);
    }