Which is the fastest way of reading a text file? Do new features of 1.7 offer any functionality in which we can read the text file faster?
Asked
Active
Viewed 8,037 times
2

Andrew Thompson
- 168,117
- 40
- 217
- 433

user1633823
- 347
- 2
- 5
- 14
-
http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/ http://stackoverflow.com/questions/964332/java-large-files-disk-io-performance https://blogs.oracle.com/slc/entry/javanio_vs_javaio – nhahtdh Sep 01 '12 at 03:55
-
http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly – nhahtdh Sep 01 '12 at 04:03
-
2umm, current version of Java is 7(1.7)...anyways, try not to worry what is the "fastest" way, especially if you are just beginning to learn this stuff. Trying to optimize programs often just ends up making the program slower because you're adding code. – Jimmt Sep 01 '12 at 04:07
-
*"When seeking to improve performance: prototype and measure first, optimize only if needed."* From the pop-up of the [tag:performance] tag. ;) – Andrew Thompson Sep 01 '12 at 04:35
-
http://stackoverflow.com/questions/12220052/regarding-reading-a-file-and-optimizing-the-performance and http://stackoverflow.com/questions/12225297/faster-than-buffered-reader – Peter Lawrey Sep 01 '12 at 07:25
-
You can read millions of lines per second with `BufferedReader.readLine()`. That's fast enough for most purposes. – user207421 Sep 12 '20 at 06:07
2 Answers
1
I would suggest using a BufferedReader since it is made to read faster than something like just the InputStream.
String filePath = ".../.../file.txt";
BufferedReader in = new BufferedReader(new FileReader(new File(pathPath)));
String line = null;
while((line = in.readLine()) != null)
System.out.println(line);
in.close(); //very important to close streams
You would also need try catches. You could also try a Scanner but I do not think it is as fast as a BufferedReader.

Axelrod360
- 113
- 7
-1
Java 1.4+ includes the new nio (New Input/Output) package for faster file transfer and retrieval. Consider taking a look at a similar answer: Java NIO FileChannel versus FileOutputstream performance / usefulness or the official examples from the Oracle website: http://docs.oracle.com/javase/1.4.2/docs/guide/nio/example/index.html