【问题标题】:DataInputStream and OutputStream write/read string with lengthDataInputStream 和 OutputStream 写入/读取字符串的长度
【发布时间】:2013-11-03 02:01:27
【问题描述】:

如何用DataInputStream读取String,用这段代码存储:

DataOutputStream dataOut = new DataOutputStream (out); // Some other stream
String title = processed.getTitle();
dataOut.writeInt(title.length());
dataOut.writeBytes(title);

【问题讨论】:

  • 读入?错误你可以从 - DataInputStream 中读取
  • 试试这个链接 - e-geek.pl。我写了一篇关于流操作的简单文章。它的缺点是波兰语和谷歌翻译不能很好地处理它;P

标签: java io java-io


【解决方案1】:

您可以使用ByteArrayOutputStreamByteArrayInputStream 以及一个字节数组作为中间缓冲区..

ByteArrayOutputStream out = new ByteArrayOutputStream();

// Some other streams
DataOutputStream dataOut = new DataOutputStream (out); 
String title = processed.getTitle();
dataOut.writeInt(title.length());
dataOut.writeBytes(title);

ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
DataInputStream dataIn = new DataInputStream(in);

【讨论】:

    【解决方案2】:
    dataOut.writeUTF(title);
    // ...
    String title = dataIn.readUTF();
    

    ...如果以这种格式编写时标题不需要超过 65533 个字节:请参阅 Javadoc。

    【讨论】:

      【解决方案3】:

      你可以这样读。

      DataInputStream dataIn = new DataInputStream (input);
      int length = dataIn.readInt();
      byte[] array = new byte[length];
      dataIn.read(array);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-23
        • 2021-12-04
        • 2011-10-12
        相关资源
        最近更新 更多