【问题标题】:How to send a string array using sockets and objectoutputstream如何使用套接字和 objectoutputstream 发送字符串数组
【发布时间】:2011-10-30 22:21:06
【问题描述】:

我有这个发送字符串或整数,但如果我想发送一个字符串数组我应该使用什么?

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

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

提前致谢

【问题讨论】:

  • 我强烈建议使用.getBytes( "UTF-8" ) 为您的字符串获取安全的字节编码。

标签: java sockets objectoutputstream


【解决方案1】:

只写数组

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

如果您使用ObjectOutputStream,则无需为字节数组而烦恼 - 该类提供了读取和写入整个对象的高级方法。

同样:

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

如果您使用原始的低级 OutputStream 类,则只需要使用 write(byte[]) 方法。

【讨论】:

  • 更不用说安全的字符串编码了。
  • 如何使用ObjectInputStreamreadObject()读取相同的写入数组?
  • @Kush:通过投射。数组是对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
相关资源
最近更新 更多