简体   繁体   English

将DataOutputStream与Java中的String进行比较

[英]Compare DataOutputStream to String in Java

I have a DataOutputStream I would like to copy into a string. 我有一个DataOutputStream我想复制成一个字符串。 I've found a lot of tutorials on converting DataOutputStreams by setting it to a new ByteArrayOutputStream, but I just want to read the string it sends when it flushes, and my DataOutputStream is already assigned to an output stream though a socket. 我已经找到很多关于转换DataOutputStreams的教程,通过将它设置为新的ByteArrayOutputStream,但我只想读取它刷新时发送的字符串,并且我的DataOutputStream已经通过套接字分配给输出流。

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

If the context is helpful, I'm trying to read the output stream of a server and compare it to a string. 如果上下文有用,我正在尝试读取服务器的输出流并将其与字符串进行比较。

the flush method will flush, ie force write, anything buffered, but not yet written. flush方法将刷新,即强制写入,缓冲但尚未写入的任何内容。

In the code below, try putting a breakpoint on the second call to writeUTF - if you navigate to your file system you should see the created file, and it will contain "some string". 在下面的代码中,尝试在第二次调用writeUTF时设置断点 - 如果导航到文件系统,您应该看到创建的文件,它将包含“some string”。 If you put the break point on flush, you can verify that the content has already been written to file. 如果将断点设置为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();
    }
}

As such, you cannot extract the data from the DataOutputStream object, but in the example above we off course have those strings in the write calls. 因此,您无法从DataOutputStream对象中提取数据,但在上面的示例中,我们当然在写入调用中具有这些字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM