Java 输入和输出

发布于 2024-11-03 10:09:12 字数 379 浏览 4 评论 0原文

解释以下用于将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七分※倦醒 2024-11-10 10:09:12

文件只包含字节,因此最终都以字节形式结束。

字符串已经是字符流。当您将字符串写入文件时,它必须将其转换为字节流。

一个 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.

零度° 2024-11-10 10:09:12

来自 DataOutputStream javadoc

数据输出流让
应用程序写入原始Java数据
类型到输出流中
便携式方式。然后应用程序可以
使用数据输入流来读取
数据返回。

来自 PrintWriter javadoc

打印格式化的表示
对象到文本输出流。

一切都只是字节,但它们代表不同的东西。使用DataOutpuStream,您可以获得可以直接读回原始Java 类型int 的字节,而使用PrintWriter 则不行。

From DataOutputStream javadoc:

A data output stream lets an
application write primitive Java data
types to an output stream in a
portable way. An application can then
use a data input stream to read the
data back in.

From PrintWriter javadoc

Prints formatted representations of
objects to a text-output stream.

Everything is just bytes, but they represent different things. With a DataOutpuStream you get bytes that you can read back directly to your primitive Java type int, whereas with a PrintWriter you don't.

依 靠 2024-11-10 10:09:12

可能会重复已经说过的内容,但只是为了使其更明确:

当您使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文