Reputation: 967
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.
Upvotes: 0
Views: 1457
Reputation: 44957
The statement
x = in.readLine()
stores the content of a line in variable x
. This string does not contain any line breaks. If you simply write the content of x
into a file using
out.write(x)
you will of course lose all the line-breaks. Try to change it to
out.write(x + "\n")
By the way: the condition in your while-loop should throw away every second line. Is this intended?
Why are you trying to work with XML files in a line-by-line manner? Using some XML framework would seem more appropriate.
Another remark: your current code looks like a strange re-implementation of "TEE". Are you sure that there is a good reason to re-implement it?
Upvotes: 1
Reputation: 36431
If you want to copy the content of a file then use Stream
s not Reader
s/Writer
s.
Stream
s operate at byte level and there is no interpretation while reading and writing bytes.
Reader
s/Writer
s operate at character level and some transformations may occur during reading/writing especially charset encoding and/or end-of-lines.
You also forget to output an end-of-line.
Upvotes: 1
Reputation: 1010
After out.write(x);
, add the following line:
out.newLine();
This will add the missing carriage returns.
Upvotes: 2