4

I have a DataOutputStream I would like to copy into a string. 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.

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.

Andrew Feather
  • 173
  • 2
  • 14

1 Answers1

0

the flush method will flush, i.e. force write, anything buffered, but not yet written.

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". If you put the break point on flush, you can verify that the content has already been written to file.

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.

Hervian
  • 1,066
  • 1
  • 12
  • 20