Java 输入和输出
解释以下用于将 int i 输出到文件的两个代码片段的输出之间的区别:
i)
PrintWriter outfile = new PrintWriter(new FileWriter("ints.txt"));
outfile.print(i);
ii)
DataOutputStream out = new DataOutputStream(new FileOutputStream("ints.dat"));
out.writeInt(i);
我认为打印机编写器采用字符串并将其转换为 unicode 字符流,而数据输出流则转换数据项目到字节序列。
您还想补充什么吗?
Explain the difference between the outputs of the following two fragments of code for outputting an int i to a file:
i)
PrintWriter outfile = new PrintWriter(new FileWriter("ints.txt"));
outfile.print(i);
ii)
DataOutputStream out = new DataOutputStream(new FileOutputStream("ints.dat"));
out.writeInt(i);
I think the Printer writer takes a string and tranforms it into a stream of unicode characters, whereas dataoutput stream converts the data items to sequence of bytes.
What more would you add?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
文件只包含字节,因此最终都以字节形式结束。
字符串已经是字符流。当您将字符串写入文件时,它必须将其转换为字节流。
一个 int 是四个字节。 writeInt() 将其转换为大端数。
Files only contain byte, so it all ends up as bytes in the end.
A String is already a stream of characters. When you write a String to a file it has to turn it into a stream of bytes.
An int is four bytes. writeInt() turns it into a big endian number.
来自
DataOutputStream
javadoc:来自
PrintWriter
javadoc一切都只是字节,但它们代表不同的东西。使用
DataOutpuStream
,您可以获得可以直接读回原始Java 类型int
的字节,而使用PrintWriter
则不行。From
DataOutputStream
javadoc:From
PrintWriter
javadocEverything is just bytes, but they represent different things. With a
DataOutpuStream
you get bytes that you can read back directly to your primitive Java typeint
, whereas with aPrintWriter
you don't.可能会重复已经说过的内容,但只是为了使其更明确:
当您使用 printwriter 时,并说您的 int 值为 65 -
当您使用时 print writer 将打印 2 个字符:“6”和“5”一个输出流,它打印字节,因此它将向文件写入一个值为 65 的字节——这恰好是 ASCII/UTF-8 中“A”的字符代码,因此如果您在文本编辑器中打开该文件你会看到一个“A”字符——而不是上面的“6”后跟“5”。
possibly repeating what was already said, but just to make it more explicit:
when you use a printwriter, and say you have an int value of 65 -- the print writer will print 2 characters: '6' and '5'
when you use an outputstream, this prints bytes so it will write to the file a byte with the value of 65 -- this happens to be the character code in ASCII/UTF-8 for 'A' so if you open up the file in a text editor you will see an "A" character -- rather than '6' followed by '5' as above.