【问题标题】:Compare DataOutputStream to String in Java将 DataOutputStream 与 Java 中的 String 进行比较
【发布时间】:2016-07-10 00:35:21
【问题描述】:

我有一个 DataOutputStream 我想复制到一个字符串中。我找到了很多关于通过将 DataOutputStreams 设置为新的 ByteArrayOutputStream 来转换它的教程,但我只想读取它在刷新时发送的字符串,并且我的 DataOutputStream 已经通过套接字分配给输出流。

output.writeUTF(input.readLine());
output.flush();

如果上下文有帮助,我会尝试读取服务器的输出流并将其与字符串进行比较。

【问题讨论】:

  • 好吧,你在那儿写输出,而不是读它。你是服务员吗?如果服务器是“输入”,你为什么不打印(或其他)你刚刚用readLine()读到的那行?
  • 我知道flush正在写它。我将如何使用 readline() 阅读?
  • 呃,“阅读”是 input.readLine() 所做的。

标签: java string compare dataoutputstream


【解决方案1】:

flush 方法将刷新,即强制写入,任何缓冲但尚未写入的内容。

在下面的代码中,尝试在第二次调用 writeUTF 时设置断点 - 如果您导航到文件系统,您应该会看到创建的文件,并且它将包含“一些字符串”。如果你把断点放在flush上,你可以验证内容是否已经被写入文件。

public static void test() throws IOException {
    File file = new File("/Users/Hervian/tmp/fileWithstrings.txt");
    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream(file));
        dos.writeUTF("some string");
        dos.writeUTF("some other string");
        dos.flush();//Flushes this data output stream. This forces any buffered output bytes to be written out to the stream.
    } finally {
        if (dos!=null) dos.close();
    }
}

因此,您无法从 DataOutputStream 对象中提取数据,但在上面的示例中,我们当然在写入调用中有这些字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2015-12-29
    • 1970-01-01
    • 2020-07-16
    • 2019-10-19
    • 2013-06-09
    相关资源
    最近更新 更多