在 Java 中将 long(原始类型)写入文件
大家好,
我有一个 long 数组,我想将其写入 .txt 文件,稍后可以在 gedit 中打开该文件(每行一个数字)。我通过使用 System.currentTimeMillis() 的两个实例相减来获得这些值。
我使用以下代码:
BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
for (int i = 0; i < USER_LIMIT; ++i) {
out.write(latency[i] + "\n");
}
out.close();
当查看文件时,我确实看到:
0
1
1
0
我相信字符串连接将 long 转换为整数。如果我使用 DataOutputStream,那么我无法使用 gedit 或任何记事本/文本编辑器读回它,它看起来就像垃圾(我相信它正在写入字节)。
有人可以告诉我如何解决我的问题吗?
非常感谢!
Hi all,
I have an array of long that I would like to write into a .txt file that I can later open in gedit (one number per line). I get those values by using a subtraction of two instances of System.currentTimeMillis().
I use the following code:
BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
for (int i = 0; i < USER_LIMIT; ++i) {
out.write(latency[i] + "\n");
}
out.close();
When looking at the file, I do see:
0
1
1
0
I believe the string concatenation converted the long into an integer. If I use the DataOutputStream, then I cannot read it back with gedit or any notepad/text editor, it just looks like garbage (I believe it's writing bytes).
Would anyone please let me know how I can fix my problem please?
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的代码没有任何问题。您所认为的
延迟
...事实并非如此。产生:
当您遇到这样的代码问题时,编写一个小测试用例来缩小问题范围通常是有益的。
There is nothing wrong with your code. What you think is in
latency
... isn't.produces:
When you're having a problem with code like this, it's often beneficial to write a small test case to narrow down the problem.
转换为 Long 并使用 toString:
或者仅使用静态 toString:
Cast to a Long and use toString:
Or just use the static toString:
当您使用 DataOutputStream 写入 long 数据时,它使用的数据编码与 gedit 无法理解的不同。
文本文件最常用的编码之一是 ASCII。这样每个字节代表表中的一个字符。该表有 128 个字符。当您使用 Java 将字符串写入文件时,就会发生这种情况,并且 gedit 可以理解该编码。如果将 long 转换为字符串,long 的最大大小将如下所示:9223372036854775807。这将占用 19 个字节。
Java 中的 long 是 64 位或 8 个字节。当您使用 DataOutputStream 时,long 将作为 8 个字节写入文件。像 gedit 这样的文本编辑器不理解这种编码。
使事情变得更加复杂的是 UTF-8 等编码。
When you use DataOutputStream to write a long it is using a different encoding of your data than gedit understands.
One of the most common encodings used for text files is ASCII. With this each byte represents a character in a table. This table has 128 characters. When you write a string to a file using Java the way you're doing it this is what is happening and gedit understands that encoding. If you convert a long to a string the maximum size a long can be would look like: 9223372036854775807. That would take up 19 bytes.
A long in Java is 64 bits or 8 bytes. When you use DataOutputStream a long gets written to the file as 8 bytes. A text editor like gedit does not understand this encoding.
What further complicates things is encodings such as UTF-8.
您不需要将换行符附加到数字上,因此您可以将它们分开并避免此问题。试试这个:
You don't need to append the newline to the number, so you can break them apart and avoid this problem. Try this: