user2681872
user2681872

Reputation:

BufferedReader does not read all the lines in text file

I have a function.

public ArrayList<String> readRules(String src) {
    try (BufferedReader br = new BufferedReader(new FileReader(src))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
            lines.add(sCurrentLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return lines;
}

My file have 26.400 lines but this function just read 3400 lines at end of file. How do I read all lines in file. Thanks!

Upvotes: 0

Views: 8306

Answers (3)

Andr&#233;s Sanchez
Andr&#233;s Sanchez

Reputation: 119

You can also cast into a List of strings using readAllLines() and then loop through it.

List<String> myfilevar = Files.readAllLines(Paths.get("/PATH/TO/MY/FILE.TXT"));
for(String x : myfilevar)
{
    System.out.println(x);
}

Upvotes: 0

Matias Cicero
Matias Cicero

Reputation: 26281

Why don't you use the utility method Files.readAllLines() (available since Java 7)?

This method ensures that the file is closed when all bytes have been read or an IOException (or another runtime exception) is thrown.

Bytes from the file are decoded into characters using the specified charset.

public ArrayList<String> readRules(String src) {
    return Files.readAllLines(src, Charset.defaultCharset());
}

Upvotes: 2

padawan
padawan

Reputation: 1315

  while ((sCurrentLine = br.readLine()) != null)

It is likely that you have an empty line or a line that is treated as null.

Try

while(br.hasNextLine())
{
    String current = br.nextLine();
}

Edit: Or, in your text file, when a line is too long, the editor automatically wraps a single line into many lines. When you don't use return key, it is treated as a single line by BufferedReader.

Notepad++ is a good tool to prevent confusing a single line with multiple lines. It numbers the lines with respect to usage of return key. Maybe you could copy/paste your input file to Notepad++ and check if the line numbers match.

Upvotes: 0

Related Questions