Wednesday, November 7, 2012

Read file content. Write content to file

Simple utility methods for reading from and writing to a file


public static String readFile(File file) throws Exception
{
 BufferedReader br = null;
 java.io.FileReader fr = null;
 try {
 fr = new java.io.FileReader(file);
 br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new FileNotFoundException(e.getMessage());
}
StringBuffer sb = new StringBuffer();
String str= null;
try
{
while((str=br.readLine()) != null)
{
 sb.append(str);
 sb.append("\n");
}

}
    catch(Exception e)
{
e.printStackTrace();
throw new Exception(e.getMessage());
}
    finally
    {
    try {
    fr.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    return sb.toString();
  }
public static void writeFile(File file,String content) throws Exception
{
BufferedWriter out=null;
     try{
       // Create file
       FileWriter fstream = new FileWriter(file);
           out = new BufferedWriter(fstream);
       out.write(content);
       //Close the output stream
       out.close();
       }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         throw new Exception(e.getMessage());
       }
       finally
       {
        if(out != null)
        {
        try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
       }
}

No comments:

Post a Comment