This method is convenient to read all lines in a single operation but returns a list of strings and strips line terminators from the end of each line. We can easily handle this by joining each of the elements of the list with a line separator, as shown below:. Paths ; import java. Java 8 introduced Files.
It takes the path to the file and overloaded it to accept the charset for decoding. Like Files. Java 8 also introduced BufferedReader. This is demonstrated below using Stream:. BufferedReader ; import java. FileReader ; import java. Java 11 introduced the Files. It takes a path to the file and overloaded to accept the charset used for decoding from bytes to characters. Several third-party libraries provide utility methods for working with files. Guava provides the Files. Charsets ; import com.
For an ImmutableList , use Files. Note that both these methods strip line-termination characters from the end of each line. Joiner ; import com. Like Guava library, Apache Commons IO FileUtils class provides the readFileToString method that allows you to read the contents of any file into a string using the specified charset for converting Bytes from the file into characters.
FileUtils ; import java. It takes an InputStream and renders its contents as a String, as shown below:. IOUtils ; import java. FileInputStream ; import java. We can also construct a Scanner that produces values scanned from the specified file.
This is demonstrated below using the try-with-resources block to automatically takes care of scanner. In plain Java, we can open an input stream of bytes using InputStream and keep reading bytes of data from it into a byte array using its read method. Finally, to get output in the string format, pass the byte array to the String constructor with a charset for decoding. IOException ;. FileInputStream fileInputStream ;. Join the Discussion If you liked this article, then please share it on social media.
Other Popular Articles How to get MD5 checksum for any given file in Java? How to create new file? How to check if file is Writable or not? File ; import java. FileInputStream ; import java. BufferedReader is very simple and high performance technique of reading text files in Java. It reads the text from a character input stream. It does the buffering of characters, arrays and lines for efficient reading.
FileReader is used for reading streams of characters. For reading streams of raw bytes, try using a FileInputStream. Internally it uses BufferedReader to read the file. Stream API methods can be used like forEach , map to get record with each line of the file.
0コメント