使用 DataOutputStream 时出现奇怪的输出
我正在使用 Java IO 的 DataOutputStream 来写入文件,但是当我执行程序时,我没有得到正确的输出,而是得到了奇怪的字符。 -虽然我注意到只有使用 writeUTF(String str) 方法写入字符串才有效,但即使使用 writeBytes(String s) 也会产生一个奇怪的字符,该字符应该是空格字符-写入文件的代码部分如下,任何想法可能的原因,也许与编码有关?提前致谢。
FileOutputStream fs= new FileOutputStream("Path/to/my/file");
DataOutputStream ds = new DataOutputStream(fs);
ds.writeBoolean(false);
ds.writeChar('A');
ds.writeInt(42);
ds.writeBytes("test1");
ds.writeUTF("test2");
fs.close();
I'm using DataOutputStream of Java IO in order to write to a file but when I execute the program, I don't get the correct output, instead, I get weird characters. -Although I have noticed that only writing strings using the writeUTF(String str) method works, even using writeBytes(String s) produces a weird character that's supposed to be space character- The code part of writing to file is below, any ideas on possible causes, maybe something related to encodings? Thanks in advance.
FileOutputStream fs= new FileOutputStream("Path/to/my/file");
DataOutputStream ds = new DataOutputStream(fs);
ds.writeBoolean(false);
ds.writeChar('A');
ds.writeInt(42);
ds.writeBytes("test1");
ds.writeUTF("test2");
fs.close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DataOutputStream
类被定义为写入字节流,而不是字符流。这种字节流的目的是有效且可移植地存储,无论人类是否可以读取它。如果您需要人类可读的文本文件,请使用 XML 编写器。
顺便说一句,您得到的输出是正确的,而是您的理解是错误的。您可能只需要阅读并理解文档 随课程而来。
The
DataOutputStream
class is defined to write a stream of bytes, not a stream of characters. This stream of bytes has the purpose of being efficiently and portably stored, no matter whether humans can read it or not.If you want human-readable text files, use an XML writer.
By the way, the output you get is correct, it's rather your understanding that is wrong. You probably just need to read and understand the documentation that comes with the class.
数据流用于二进制数据 DataOutputStream 以二进制格式写入整数,即它将整数分成 4 个字节并写入
Data Streams are for binary data DataOutputStream writing the integer in binary format, i.e. it splits the integer into 4 bytes and writes those