Reading file to string in Java with performance stats (IO, NIO, Apache commons-io, Google Guava)

This article provides all the ways of reading file into a String in Java along with performance statistics.

Performance statistics

Below are time taken by file reading methods with 50MB file. To get fair statistics, 5 rounds of method call are counted.

Reading method 50 MB file read time (Milli-Seconds)
Java java.io.FileReader 88420, 83222, 85353, 83131, 85252
Java java.io.BufferedReader 83263, 85080, 83288, 84097, 83171
Java NIO java.nio.file.Files 59, 37, 35, 36, 35
Apache common-io org.apache.commons.io.FileUtils 168, 113, 104, 145, 136
Google com.google.common.io.Files 63, 61, 58, 59, 56

java.io.FileReader



java.io.BufferedReader

java.nio.file.Files

org.apache.commons.io.FileUtils



com.google.common.io.Files



Complete code with to test reading & performance

Here is the complete code which tests reading of file into Sting, print it. Also measures performance time take of all methods using Java Instant & Duration. Takes 5 readings to get fair stats.

Output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *