我有這個發送字符串或整數,但如果我想發送一個字符串數組我應該使用什麼?提前如何使用套接字和objectoutputstream發送字符串數組
// A string ("Hello, World").
out.write("Hello, World".getBytes());
// An integer (123).
out.write(ByteBuffer.allocate(4).putInt(123).array());
感謝
我有這個發送字符串或整數,但如果我想發送一個字符串數組我應該使用什麼?提前如何使用套接字和objectoutputstream發送字符串數組
// A string ("Hello, World").
out.write("Hello, World".getBytes());
// An integer (123).
out.write(ByteBuffer.allocate(4).putInt(123).array());
感謝
如果您使用ObjectOutputStream
只寫陣列
ObjectOutputStream out = ...
String[] array = ...
out.writeObject(array);
,就沒有必要使用字節數組渣土約 - 類提供了高層次的方法讀取和寫入整個對象。
同理:
out.writeInt(123);
out.writeObject("Hello, World");
你只需要如果你使用的原料,低層次的OutputStream
類使用write(byte[])
方法。
我強烈建議使用'.getBytes(「UTF-8」)'爲您的字符串獲取安全的字節編碼。 –