Non-blocking (NIO) reading of lines
I understand you guys don't like limitations, but in case the one asking don't have access to IO package or not allowed to import it for some reason the top answer is not helpful...
Two ways to do it completely IO free:
java.nio.file.Files.lines
, Returns a stream of lines, which is part of .util package and not .io package like bufferedReader.java.nio.file.Files.readAllLines
, Returns a collection of lines which is iterable. Proceed to use aniterator
orfor each
to extract a single line.
cheers
Oracle introduces a example in the tutorial. https://docs.oracle.com/javase/tutorial/essential/io/file.html#streams
Path file = ...;
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.println(x);
}
Why? NIO doesn't support reading lines. You can read millions of lines a second with BufferedReader.readLine().
I suggest that is sufficient.
Using java.nio.file.Files
you can do:
Path path = FileSystems.getDefault().getPath("/path/to", "file.txt");
Files.lines(path).forEach(line ->
// consume line
);
As the lines(path)
method returns a Stream
, you can take advantage of any other method of the Stream API, like reading just the first line (if one exists) with:
Optional<String> firstLine = Files.lines(path).findFirst();