简体   繁体   English

DataOutputStream只写一个字符串Java

[英]DataOutputStream only writes a string Java

DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("myfile.txt"));
dataOut.writeUTF("HEY");   // write HEY
dataOut.writeShort(1);     // writes nothing

I am trying to use DataOutputStream to write something in my text file. 我正在尝试使用DataOutputStream在我的文本文件中写一些东西。 However, it only writes a string, not an integer or short. 但是,它只写一个字符串,而不是整数或短整数。 I do not understand why it only writes strings. 我不明白为什么它只写字符串。 Please help. 请帮忙。

NOTE: Despite calling the file myfile.txt , this is a binary not a text format so you can't expect to read it as text eg with a text editor and see the short value. 注意:尽管调用了文件myfile.txt ,但它是二进制文件而不是文本格式,因此您不能期望将其读取为文本,例如使用文本编辑器并看到简短的值。

This works fine if you close the file and read it the same way it was written. 如果您关闭文件并以与写入文件相同的方式读取文件,则此方法可以正常工作。

try (DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("myfile.txt"))) {
    dataOut.writeUTF("HEY");   // write HEY
    dataOut.writeShort(1);
}
try (DataInputStream dataIn = new DataInputStream(new FileInputStream("myfile.txt"))) {
    System.out.println("string: " + dataIn.readUTF());
    System.out.println("short: " + dataIn.readShort());
}

prints 版画

string: HEY
short: 1

Most likely you expected the file to be text. 您最有可能希望文件为文本。

try (PrintWriter dataOut = new PrintWriter(new FileOutputStream("myfile.txt"))) {
    dataOut.println("HEY");   // write HEY
    dataOut.println(1);
}
try (Scanner dataIn = new Scanner(new FileInputStream("myfile.txt"))) {
    System.out.println("string: " + dataIn.nextLine());
    System.out.println("short: " + dataIn.nextShort());
}

prints 版画

string: HEY
short: 1

and the file contains 并且文件包含

HEY
1

You have produced no evidence for your assertion. 您没有为您的主张提供任何证据。 Neither writeUTF() nor writeInt() produces text. writeUTF()writeInt()都不产生文本。 They both produce binary data. 它们都产生二进制数据。 You should not try to save this data in a file with the .txt extension (and you should not try to read it with a text editor). 您不应尝试将此数据保存在扩展名为.txt的文件中(也不应尝试使用文本编辑器读取数据)。 The only way you can read this data is with a DataInputStream . 读取此数据的唯一方法是使用DataInputStream

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

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