Delete and rename file in Java

advertisements

I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.

import java.io.*;

    class ModifyXML {

         public void readMyFile(String inputLine) throws Exception
         {

            String record = "";

            File outFile = new File("tempFile.tmp");

            FileInputStream fis  = new FileInputStream("InfectiousDisease.xml");

            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            FileOutputStream fos = new FileOutputStream(outFile);

            PrintWriter out = new PrintWriter(fos);

            while ( (record=br.readLine()) != null )
            {
                 if(record.endsWith("<add-info>"))
                 {
                     out.println("    "+"<add-info>");
                     out.println("    "+inputLine);
                 }
                 else
                 {
                     out.println(record);
                 }

            }
           out.flush();
           out.close();
           br.close();
           //Also we need to delete the original file
           //outFile.renameTo(InfectiousDisease.xml);//Not working

         }

         public static void main (String[] args) {
             try
             {
             ModifyXML f = new ModifyXML();
             f.readMyFile("This is infectious disease data");
             }
             catch(Exception e)
             {
                 e.printStackTrace();
             }
         }
    }

Thanks


First delete the original file and then rename the new file:

File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");

if(inputFile.delete()){
   outFile.renameTo(inputFile);
}