Thursday, March 17, 2016

How to read File into String in Java 7

Before Java 7, you have to write lot of code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some API but it was not so simple like we have in python.

Whenever you convert binary data into text data, you must remember to use correct character encoding. An incorrect choice of character encoding may result in totally different or slightly different content than the original file.

Before JDK 1.7 we used to read file


InputStream inputStream = new FileInputStream("abc.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
      
String line = br.readLine();
StringBuilder sb = new StringBuilder();
      
while(line != null){
   sb.append(line).append("\n");
   line = br.readLine();
}
      
String fileAsString = sb.toString();
System.out.println("File data is : " + fileAsString);

From JDK 1.7

String fileData = new String(Files.readAllBytes(Paths.get("abc.txt")));
System.out.println("FileData  : " + fileData);

The above code uses platform's default character encoding. If you want you can use your own/custom character encoding.

 How to provide a custom character encoding 


 String fileData = new String(Files.readAllBytes(Paths.get("abc.txt")), StandardCharsets.UTF_8);
 System.out.println("FileData  : " + fileData);