Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I 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?

like image 990
manoj singh Avatar asked May 03 '11 10:05

manoj singh


People also ask

How can I get line by line in Java?

Java Scanner class provides the nextLine() method to facilitates line by line of file's content. The nextLine() methods returns the same String as readLine() method. The Scanner class can also read a file form InputStream.

What is the easiest way to read text files line by line in Java 8?

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed.

How do you read a specific line from a text file in Java?

Java supports several file-reading features. One such utility is reading a specific line in a file. We can do this by simply providing the desired line number; the stream will read the text at that location. The Files class can be used to read the n t h nth nth line of a file.


2 Answers

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. } 

UPDATE: In Java 8 you can do

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {         stream.forEach(System.out::println); } 

NOTE: You have to place the Stream in a try-with-resource block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later.

like image 164
Peter Lawrey Avatar answered Oct 20 '22 05:10

Peter Lawrey


Look at this blog:

  • Java Read File Line by Line - Java Tutorial

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

// Open the file FileInputStream fstream = new FileInputStream("textfile.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream));  String strLine;  //Read File Line By Line while ((strLine = br.readLine()) != null)   {   // Print the content on the console   System.out.println (strLine); }  //Close the input stream fstream.close(); 
like image 23
Naveed Avatar answered Oct 20 '22 04:10

Naveed