2017-07-26 56 views
0

我知道一個ObjectOutputStream/ObjectInputStream使用標題,這不是一個真正合適的用例。但無論如何,我需要使用接口DataInput和DataOutput將一些數據包裝進去。如何使用ObjectOutputStream和ObjectInputStream將(de)正確序列化爲字節數組?

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     byte[] array = serialize("test"); 
     String deserialized = deserialize(array); 

     System.out.println(deserialized); 
    } 

    private static byte[] serialize(String test) { 
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

     try { 
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); 

      objectOutputStream.writeUTF(test); 

      byteArrayOutputStream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return byteArrayOutputStream.toByteArray(); 
    } 

    private static String deserialize(byte[] array) { 
     String temp = null; 

     try { 
      ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(array)); 

      temp = objectInputStream.readUTF(); 

      objectInputStream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return temp; 
    } 
} 

我真的不知道如何得到這個工作。我是對的,問題是目前這些標題?

+0

什麼不起作用?你有例外或錯誤的結果?你也可以在你的文章中提供[最小工作示例](https://stackoverflow.com/help/mcve)。 – talex

+0

@talex它拋出一個EOFException。請看看[這裏](http://ideone.com/iIC9TI) – Tobseb

+0

你應該在你的問題中發佈你的代碼,因爲外部資源不可靠,將來有人可能會有同樣的問題,但無法理解你的問題,因爲斷開的鏈接。這次我爲你做了,但是請你今後自己做。 – talex

回答

2

您應該在關閉byteArrayOutputStream之前致電objectOutputStream.flush();

ObjectOutputStream有它的內部緩衝區,所以你只有字節數組中的字符串開頭。

+0

你能否堅持這個問題? :)當然你是對的,但這並沒有改變任何東西:http://ideone.com/dAsGdO – Tobseb

+0

你應該刷新'objectOutputStream'而不是'byteArrayOutputStream'。刷新'byteArrayOutputStream'是無用的。它總是直接寫入緩衝區。 – talex

+0

@Tobseb,在你的代碼中你應該做'objectOutputStream.writeUTF(test); \t \t \t objectOutputStream.flush(); \t \t \t byteArrayOutputStream.close();' –

相關問題