Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest method for reading from a text file in Java?

Tags:

java

file-io

I currently use:

BufferedReader input = new BufferedReader(new FileReader("filename"));

Is there a faster way?

like image 254
snake Avatar asked Dec 08 '22 07:12

snake


1 Answers

While what you've got isn't necessarily the absolute fastest, it's simple. In fact, I wouldn't use quite that form - I'd use something which allows me to specify a charset, e.g.

// Why is there no method to give this guaranteed charset
// without "risk" of exceptions? Grr.
Charset utf8 = Charset.forName("UTF-8");     
BufferedReader input = new BufferedReader(
                           new InputStreamReader(
                               new FileInputStream("filename"),
                               utf8));

You can probably make it go faster using NIO, but I wouldn't until I'd seen an actual problem. If you see a problem, but you're doing other things with the data, make sure they're not the problem first: write a program to just read the text of the file. Don't forget to do whatever it takes on your box to clear file system caches between runs though...

like image 55
Jon Skeet Avatar answered Feb 03 '23 11:02

Jon Skeet