2013-03-31 93 views
3

我有一個需要通過藍牙發送爲對象的序列化類,並且還實現了Runnable。因此,我首先設置了一些變量,然後將它作爲一個對象發送給另一個Android設備,然後該設備將其結果設置爲一個變量,並將結果返回給一個變量。我一直使用以下兩種方法來序列化我的對象,並在通過BluetoothSocket的OutputStream發送它們之前獲取一個ByteArray,並反序列化該ByteArray以獲取我的對象。通過藍牙發送序列化對象時發生StreamCorruptedException

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

+0

嘗試移除'out.flush()'或將其替換爲'out.reset()'。讓我知道如果這有效! – gauravsapiens

+0

完整堆棧跟蹤 – njzk2

+0

您沒有使用deserializeObject。你沒有測試你閱讀的緩衝區的長度或完整性。我不明白把你的對象放在一個字節數組中,而不是在藍牙OS上打開一個OOS。您不知道或無法知道緩衝區的內容是否包含完整的對象,並且從正確的位置開始。 – njzk2

回答

1

根據thisthis螺紋:

您應該使用單一ObjectOutputStreamObjectInputStream套接字的生活,也不要在插座上使用任何其他流。

其次,使用ObjectOutputStream.reset()來清除以前的值。

讓我知道這是否行得通!