[英]DataOutputStream only writes a string Java
DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("myfile.txt"));
dataOut.writeUTF("HEY"); // write HEY
dataOut.writeShort(1); // writes nothing
我正在尝试使用DataOutputStream在我的文本文件中写一些东西。 但是,它只写一个字符串,而不是整数或短整数。 我不明白为什么它只写字符串。 请帮忙。
注意:尽管调用了文件myfile.txt
,但它是二进制文件而不是文本格式,因此您不能期望将其读取为文本,例如使用文本编辑器并看到简短的值。
如果您关闭文件并以与写入文件相同的方式读取文件,则此方法可以正常工作。
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());
}
版画
string: HEY
short: 1
您最有可能希望文件为文本。
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());
}
版画
string: HEY
short: 1
并且文件包含
HEY
1
您没有为您的主张提供任何证据。 writeUTF()
和writeInt()
都不产生文本。 它们都产生二进制数据。 您不应尝试将此数据保存在扩展名为.txt的文件中(也不应尝试使用文本编辑器读取数据)。 读取此数据的唯一方法是使用DataInputStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.