Android 套接字连接-读取XML文件时插入垃圾字符
在Android中,我试图通过打开两台设备之间的套接字连接,在它们之间传输XML文件。我能够成功找到设备,连接并打开插座连接 问题是——当我读取第一台设备发送的xml文件时,发现其中插入了很多垃圾字符。例如,设备发送的以下持续XML文件:Android 套接字连接-读取XML文件时插入垃圾字符,android,file-io,bluetooth,Android,File Io,Bluetooth,在Android中,我试图通过打开两台设备之间的套接字连接,在它们之间传输XML文件。我能够成功找到设备,连接并打开插座连接 问题是——当我读取第一台设备发送的xml文件时,发现其中插入了很多垃圾字符。例如,设备发送的以下持续XML文件: <?xml version="1.0" encoding="ISO-8859-1" ?> <note> <to>Tove</to> <from>Jani</fro
<?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>
以下是编写XML文件的代码:
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);
}
我坚信读取clinet上的socket输入流并从中创建XML文件是错误的。不知道是什么?我是否正在向XML文件写入任何控制字符。我的观点还得到了一个事实的进一步支持,即在一个较大的XML文件中,在多个位置(可能一组用于写入一个缓冲区?)您在写入时使用的是
ObjectOutputStream
,而不是在读取时使用的
ObjectOutputStream
用于序列化可序列化对象以及原语,因此当您写入字节数组时,它包含类型标记信息
您需要更改客户端代码以使用
ObjectInputStream
,或者在编写时只使用“普通”的OutputStream
。这就是为什么必须记录您正在使用的协议的原因。忽略它会让您感到愚蠢!非常感谢您的回复!它起到了很好的作用!
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);
}
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);
}