我有一个DataOutputStream我想复制成一个字符串。我已经找到很多关于转换DataOutputStreams的教程,方法是将它设置为新的ByteArrayOutputStream,但我只想读取它刷新时发送的字符串,并且我的DataOutputStream已经通过套接字分配给输出流。
output.writeUTF(input.readLine());
output.flush();
如果上下文有用,我正在尝试读取服务器的输出流并将其与字符串进行比较。
答案 0 :(得分:0)
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对象中提取数据,但在上面的示例中,我们当然在写入调用中有这些字符串。