Java 8 Stream – Read a file line by line
In Java 8, you can use Files.lines to read file as Stream. A new method lines() has been added since 1.8, it lets BufferedReader returns content as Stream.
Favourite tutorials for developers
In Java 8, you can use Files.lines to read file as Stream. A new method lines() has been added since 1.8, it lets BufferedReader returns content as Stream.
This article explains the Java 8 Stream.flatMap and how to use it. In Java 8, we can use the flatMap to convert the above 2 levels Stream into one Stream level or a 2d array into a 1d array.
Long live the Scanner class, a few examples for self-reference.
This article shows how to convert a file into a hexadecimal (hex) representative format. The idea is to read the file into an InputStream and uses String.format(%X) to convert each byte into a hex code.
This article shows a few ways to save a byte[] into a file. For JDK 1.7 and above, the NIO Files.write is the simplest solution to save byte[] to a file. FileOutputStream is the best alternative. If we have Apache Commons IO, try FileUtils.
In Java, we can use Files.readAllBytes(path) to convert a File object into a byte[]. Before Java 7, we can initiate a new byte[] with a predefined size (same with the file length), and use FileInputStream to read the file data into the new byte[]. We also can use FileUtils from Apache Commons IO to read the file.
In Java, we use FileInputStream to read bytes from a file, such as an image file or binary file. The FileInputStream.read() reads a byte at a time, and it will return a -1 if it reached the end of the file. The FileInputStream.available() to check the remaining bytes that can be read. The FileInputStream.read(byte b[]) to read predefined bytes into a byte array; it will significantly increase the read performance. The common practice uses BufferedInputStream to wrap the FileInputStream to provide a buffer cache to increase the read performance. It’s also common to use InputStreamReader to convert FileInputStream to BufferedReader, and read it line by line.
Here is another example to show how to read a file in Java with BufferedInputStream and DataInputStream classes. The readLine() from the type DataInputStream is deprecated. Sun officially announced this method can not convert property from bytes to characters. It’s advised to use BufferedReader.
In Java, the InputStreamReader accepts a charset to decode the byte streams into character streams. We can pass a StandardCharsets.UTF_8 into the InputStreamReader constructor to read data from a UTF-8 file. In Java 7+, many file read APIs start to accept charset as an argument, making reading a UTF-8 very easy.
This article focus on a few of the commonly used methods to read a file in Java. 1 – Files.lines, return a Stream (Java 8), 2 – Files.readString, returns a String (Java 11), max file size 2G. 3 – Files.readAllBytes, returns a byte[] (Java 7), max file size 2G. 4 – Files.readAllLines, returns a List