套接字连接 - 读取XML文件插入垃圾字符

use*_*195 2 file-io android bluetooth

在Android中,我试图通过在它们之间打开套接字连接来在两个设备之间传输XML文件.我能够成功找到设备,连接并打开套接字连接.

问题是 - 当我读取第一个设备发送的xml文件时,发现插入了很多垃圾字符.例如,设备发送的以下XML文件:

  <?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>
Run Code Online (Sandbox Code Playgroud)

如下其他设备收到:

  ¬í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>
Run Code Online (Sandbox Code Playgroud)

在这个XML文件中看到的垃圾字符被插入多个点以获得更大的XML文件.这是在客户端上读取XML文件的代码:

 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);
}
Run Code Online (Sandbox Code Playgroud)

这里是Ans用于编写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);
 }
Run Code Online (Sandbox Code Playgroud)

我坚信在clinet上读取套接字输入流并从中创建XML文件时出错.不确定它是什么?我是否将任何控制字符写入XML文件.在更大的XML文件中,在多个地方(可能是一组用于编写一个缓冲区?)中找到类似的垃圾字符这一事实进一步支持了我的信念.

Lau*_*ves 5

你正在使用ObjectOutputStream写入,但不是在读取.

ObjectOutputStream 用于序列化Serializable对象和基元,因此当您编写一个字节aray时,它包含类型标记信息.

您需要更改要使用的客户端代码ObjectInputStream,或者OutputStream在编写时使用"plain" .