Tuesday, August 4, 2015

[Java] Reading a File Content

Sample code to read a file content.



public static String read(String absoluteFilePath){
InputStream inputStream = null; 
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;    
String  record = null;
StringBuilder stringBuilder = new StringBuilder();
try{
inputStream = new FileInputStream(absoluteFilePath);
inputStreamReader = new InputStreamReader(inputStream);
//Open input stream test.txt for reading purpose.
bufferedReader = new BufferedReader(inputStreamReader);
while ((record = bufferedReader.readLine()) != null) {
stringBuilder.append(record+"\n");
}     
}catch(Exception e){
LOG.error("Problem in reading " + absoluteFilePath + " file.");
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
LOG.error("Problem in closing " + absoluteFilePath + " file.");
e.printStackTrace();
}
}
     
return stringBuilder.toString();
}

No comments:

Post a Comment