Wednesday 10 August 2016

Reading file in Java


Reading file data is something used day to day life of a developer. Java had continuously  worked on the improvisation of file reading and writing as these are heavy process sometime and memory consuming.

Lets take case by case :

1. Reading a file data using FileReader : 

Method to used :

public static String readFile(String filePath) {
  StringBuilder sb = new StringBuilder();
  BufferedReader br = null;
  try {
   br = new BufferedReader(new FileReader(filePath));
   String line = br.readLine();
   while (line != null) {
    sb.append(line);
    sb.append("\n");
    line = br.readLine();
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally {
   if(br!=null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return sb.toString();
 }   


2. Reading a file data using NIO: 

Method to used :

public static String readFileUsingNio(String filePath){
String content = null;
try {
content = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (Exception e) {
e.printStackTrace();
}
return content;


There are other libraries available of apache common etc where utility of reading file is given.

But as an Architect I feel adding Non Blocking I/O  features in Java 7  is being one of the finest revolution in the I/O  operation . It is always recommended to use Java features are they are fully trusted and robust. Using lesser third party libraries is always advisable as lesser dependencies means lesser chances of getting the bug and code maintainability remains cleans. 

No comments:

Post a Comment