Often you might want to read a file into a String for further processing with guava splitter, count the number of words in a file or split a string by a delimiter. This example will demonstrate how to read the content of a file into a String in java using BufferedReader, Scanner, NIO, java 8 streams, guava and apache commons. In the set up we create a constant that represents a path to the file. Using the class loader we will get the resource's URI to use through each snippet. A word of caution, if you are reading in a very large file you will need to worry about memory consumption you may look for alternatives.
Setup
File contents
This is the content of the file-to-string.txt file.
Straight up Java
BufferedReader
Using a BufferedReader we will read entire text file into a string.
Scanner
This snippet will show how to read file contents into a string using Scanner object.
Java 7 File I/O
Read All Lines
This code will read a text file into a String using java 7 Files.readAllLines. First creating a Path to the file we will pass the Path and charset to Files.readAllLines which will read all lines of a file into arraylist. Next you could join the strings or just get the first line as shown below.
Read All Bytes
This snippet will convert a text file to a string by passing all the bytes of the file to the String constructor. Using java 7 Files utility we will use readAllBytes method that will read all the bytes.
Java 8
This snippet will read a text file into a string in java 8. We will create a Path from a URI and then call Files.lines which will use a stream to iterate over each line of the file. Next we will convert the stream to a string by calling Collectors.joining() which will join all the strings together.
Google Guava
Passing in the file and the character set this snippet will read all characters from a file into a String using guava.
Apache Commons
This snippet will read the contents of a file into a String using apache commons FileUtils.readFileToString.