How to read a text file as String in Java

There was no easy way to read a text file as String in Java until JDK 7, which released NIO 2. This API now provides a couple of utility methods which you can use to read entire file as String e.g. Files.readAllBytes() returns a byte array of the entire text file. You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as List of String e.g. into an ArrayList, you can use Files.readAllLines() method. This return a List of String, where each String represents a single line of the file. Prior to these API changes, I used to use the BufferedReader and StringBuilder to read the entire text file as String. You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or lower version.
Read more »