2011-08-19 108 views
2

我有這個發送字符串或整數,但如果我想發送一個字符串數組我應該使用什麼?提前如何使用套接字和objectoutputstream發送字符串數組

// A string ("Hello, World"). 
    out.write("Hello, World".getBytes()); 

    // An integer (123). 
    out.write(ByteBuffer.allocate(4).putInt(123).array()); 

感謝

+1

我強烈建議使用'.getBytes(「UTF-8」)'爲您的字符串獲取安全的字節編碼。 –

回答

6

如果您使用ObjectOutputStream只寫陣列

ObjectOutputStream out = ... 
String[] array = ...  
out.writeObject(array); 

,就沒有必要使用字節數組渣土約 - 類提供了高層次的方法讀取和寫入整個對象。

同理:

out.writeInt(123); 
out.writeObject("Hello, World"); 

你只需要如果你使用的原料,低層次的OutputStream類使用write(byte[])方法。

+0

更不用說安全的字符串編碼了。 –

+0

如何使用'ObjectInputStream'' readObject()'讀取相同的寫入數組? – Kushal

+2

@ Kush:通過鑄造它。數組是對象。 – skaffman

相關問題