【发布时间】:2013-03-21 22:29:58
【问题描述】:
我有一个序列化类,我需要通过蓝牙将其作为对象发送,并且还实现了 Runnable。因此,我首先设置了一些变量,然后将其作为一个对象发送给另一个 Android 设备执行,然后将其结果设置为一个变量,并将结果与其中一个变量一起发送回相同的对象。我一直在使用以下两种方法来序列化我的对象并在通过我的 BluetoothSocket 的 OutputStream 发送它们之前获取一个 ByteArray,并反序列化该 ByteArray 以取回我的对象。
public static byte[] serializeObject(Object o) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.flush();
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
}
public static Object deserializeObject(byte[] b) throws OptionalDataException, ClassNotFoundException, IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInputStream in = new ObjectInputStream(bis);
Object object = in.readObject();
in.close();
return object;
}
我仍然从这两种方法中得到相同的错误,所以我尝试将它与我用来通过 BluetoothSocket 的 OutputStream 发送我的 ByteArray 的方法合并,如下所示。
public void sendObject(Object obj) throws IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream( bos );
out.writeObject(obj);
out.flush();
out.close();
byte[] buf = bos.toByteArray();
sendByteArray(buf);
}
public void sendByteArray(byte[] buffer, int offset, int count) throws IOException{
bluetoothSocket.getOutputStream().write(buffer, offset, count);
}
public Object getObject() throws IOException, ClassNotFoundException{
byte[] buffer = new byte[10240];
Object obj = null;
if(bluetoothSocket.getInputStream().available() > 0){
bluetoothSocket.getInputStream().read(buffer);
ByteArrayInputStream b = new ByteArrayInputStream(buffer);
ObjectInputStream o = new ObjectInputStream(b);
obj = o.readObject();
}
return obj;
}
最后,在接收设备反序列化对象时,我得到了同样的错误,如下所示。
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readStreamHeader (ObjectInputStream.java:2102)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)
and so on...
有人可以帮忙吗?我很绝望,这已经让我死了好几个星期,我需要几天后才能工作。 :S
【问题讨论】:
-
尝试删除
out.flush()或将其替换为out.reset()。让我知道这是否有效! -
发布完整的堆栈跟踪
-
您没有使用反序列化对象。您没有测试您读取的缓冲区的长度或完整性。我不明白首先将对象放入字节数组中的意义,而不是在蓝牙操作系统上打开 OOS。您不知道或无法知道缓冲区的内容实际上包含一个完整的对象,并且从正确的位置开始。
标签: android bluetooth inputstream outputstream serializable