Friday, December 16, 2011

Java snippet to open, modify and write back to same file

Objective :
Very often you find this requirement. Sometimes you try and overcome using linux commands rather than going by the Java programming technique.

Here is a snippet that would be handy.

 public static void main(String[] args) throws IOException {
   
    // Read XML as string
    byte[] buffer = new byte[(int) new File(args[0]).length()];
    FileInputStream f = new FileInputStream(args[0]);
    f.read(buffer);
   
    // format it
        String unformattedXml = new String(buffer);
        String formattedXml = new XmlFormatter().format(unformattedXml);
       
    // Write formatted string back into same file        
        FileOutputStream pOUTPUT;
        PrintStream pPRINT;
        pOUTPUT = new FileOutputStream(args[0]);
        pPRINT = new PrintStream(pOUTPUT);
        pPRINT.println (formattedXml + "\n");
        pPRINT.close();
        System.out.println(    formattedXml );

}


Found this handy even after experience in Java programmer.


Followers