In Android, I am trying to transfer an XML file, between 2 devices, by opening a socket connection between them. I am able to successfully locate the devices, connect and open socket connection.
The issue is – when i read the xml file that is sent by first device, a lot of junk characters are found inserted in it. For example, the folllwoing XML file sent by a device:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
is received as follows by the other device:
¬íwµ<?xml version="1.0" encoding="ISO-8859-1" ?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The junk characters seen in this XML file are inserted at multiple points for a bigger XML file. Here’s the code for reading the XML file on the client:
InputStream tmpIn = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
byte[] buffer = null;
int current = 0;
try {
tmpIn = socket.getInputStream();
// create a new file
File newTempFile = new File("/mnt/sdcard/test.xml");
if(!newTempFile.exists()) {
newTempFile.createNewFile();
}
else {
newTempFile.delete();
newTempFile.createNewFile();
}
fos = new FileOutputStream(newTempFile);
try {
byte[] buffer1 = new byte[2048];
int length;
while ((length = tmpIn.read(buffer1))>0){
fos.write(buffer1, 0, length);
}
fos.flush();
fos.close();
tmpIn.close();
}
catch (IOException e) {
Log.d("Sync", "IOException: "+ e);
}
}
catch (Exception e) {
Log.d("Sync", "Exception: "+ e);
}
Ans here’s the code for writing the XML file:
File file = new File ("/mnt/sdcard/sample.xml");
byte[] fileBytes = new byte[(int) file.length()];
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(file);
fis.read(fileBytes);
// Send the file
out.write(fileBytes);
out.flush();
out.close();
}
catch (Exception e) {
Log.d("Sync", "Exception in writing file: "+ e);
}
I strongly believe that there is an error with reading the socket input stream on the clinet and creating an XML file from it. Not sure what it is? Am I writing any control characters to the XML file. My belief is further supported by the fact that similar junk characters are found in a larger XML file, at multiple places (perhaps one set for writing one buffer?)
You’re using an
ObjectOutputStreamon write, but not on read.ObjectOutputStreamis for serializing Serializable objects as well as primitives, so when you write a byte aray it includes type tagging information.You either need to change your client code to use
ObjectInputStream, or just use a “plain”OutputStreamwhen writing.