2011-08-19 110 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

相关问题