In order to follow below examples, create a text file (sample.txt) with below content.
-
java.nio.Files is an utility class, which has lot of static methods that operate on files, in the below example we are going to useFiles.lines(Path) method which returnsStream of Strings, each String represents a line in file. Alternatively we can useFiles.readAllLines(Path) as well, which returnsList of Strings, where each String represents a line from input file.
FileReader reads content of a file as a stream of characters from the file, and this class mainly intended for reading the data as text only.- It is possible to read one character at a time or an array of characters in each read method call, both examples are shown below.
In the above code,
- We can also read an array of characters in one go, and in this example we are reading 1024 characters at a time and continuing until it reaches end of file.
In the above code,
BufferedReader expects anotherjava.io.Reader as an input argument and the actual I/O operations such as reading from source file will be delegated to this underlying Reader class.- BufferedReader maintains a character array as a buffer in the memory to store chunks of characters data, so for any read request, it will return the data from the buffer as long as it has data and if it is empty then it reads the data from underlying source and fill the buffer. The default buffer size is 16KB, using this intermediate buffer it reduces number of I/O operations to the underlying source.
- BufferedReader comes handy if you want to read input from files or sockets or any other source and it is thread-safe (synchronized)
In the above code,
Above examples source code can be found at
Similar Articles
-
How to efficiently read large files in Java