Organizational Research By

Surprising Reserch Topic

How to read a large text file line by line using Java?


I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

asked Jun 18, 2015 in Core java by rajesh
0 votes
143 views



Related Hot Questions

1 Answer

0 votes
A common pattern is to use

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
}
You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.

EDIT: A less common pattern to use which avoids the scope of line leaking.

try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
        // process the line.
    }
    // line is not visible here.
}
answered Jun 18, 2015 by rajesh

...