简体   繁体   中英

Fastest way of reading a text file

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?

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.

Java have many file reading classes (FileInputStream,BufferedInputStream,RandomAccessFile,etc). Here is the link for "How to read files quickly". And you can also try Tuning Java I/O Performance .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM