Search code examples
javaxmlread-write

How to maintain the same format while reading and writing files in Java?


I am trying to read a xml file(in.arxml) and copy it into another xml file (out.arxml). When I just read the in.arxml file and display the contents in the workspace the spacing and the format is maintained and is exactly as it is in the file. However when I write this into the out.arxml file the entire ile is printed on a single line. Could somebody please tell me wht is it that I doing wrong? My code to read and write the file looks like this:

 BufferedWriter out;
 BufferedReader in;
 String x =null;
 int lineNumb=0;

 try {

            in = new BufferedReader (new FileReader("C:\\New_folder\\in.arxml"));
            out = new BufferedWriter(new FileWriter(""C:\\New_folder\\out.arxml"));
            while (in.readLine()!= null){

                x = in.readLine();
                java.lang.System.out.println(x);
                out.write(x);

                lineNumb++;
            }
            in.close();
       }catch (IOException e){
            java.lang.System.out.println("There was a problem" + e);
        }

The in.arxml file looks like :

  <?xml version="1.0" encoding="UTF-8"?>
  <xxx xmlns="http://xd3.h?.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=""http://www.w3.org/2001/XMLSchema-instance">

And the out.arxml that is written looks like this

  <?xml version="1.0" encoding="UTF-8"?> <xxx xmlns="http://xd3.h?.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=""http://www.w3.org/2001/XMLSchema-instance">

Thank you for your help in advance.


Solution

  • After out.write(x);, add the following line:

    out.newLine();
    

    This will add the missing carriage returns.