Which of the Files.readAllLines or Files.lines method is faster for reading files?
I have a file reader that returns the lines of a file as Object[]
. I am using the method lines
. Will it be faster to use readAllLines
? I'm not using stream for anything else, but I want to currentBookData
be String[]
or Object[]
.
package input;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFile {
public static Object[] currentBookData;
public static void getBookData(String path) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(path), Charset.defaultCharset())) {
currentBookData = stream.toArray();
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
readAllLines()
puts everything in memory in one go, so nothing could be faster. Don't use it if the file is large.
lines
Works faster for large files . The results were recorded using the method nanoTime
. Here are the results:
lines
: 890453203.00649
readAllLines
: 891095615.58289
For smaller files, readAllLines is faster.