英文:
How to preserve line breaks when writing ArrayList to file with ObjectOutputStream?
问题
我正在按照这个教程学习如何使用ObjectOutputStream
将ArrayList
输出到文本文件,但这会从我的原始文件中删除换行符。换句话说,我读取一个文件,对其进行处理,然后将其写回。读入的数据在整个处理过程中保持为ArrayList。在将ArrayList写入文件时,如何保留换行符?当我以ArrayList形式读入时,是否会丢失此功能?
英文:
I'm following this tutorial on how to output an ArrayList
to a text file with ObjectOutputStream
, but this removes the line breaks from my original file. In other words, I read a file in, do stuff to it, and write it back out. The data read in remain an ArrayList throughout processing. How do I preserve the line breaks when writing an ArrayList out to file? Do I lose this ability when I read it in as ArrayList?
答案1
得分: 1
你对教程的理解有误。ObjectOutputStream
不适用于输出文本文件。如果你尝试读取该类生成的文件,你会看到大量的二进制数据;换句话说,这些数据会显示为不可打印的字符,或者如果你尝试将其视为文本查看的话会显示为“垃圾”。
然而,ObjectOutputStream
不会明确地删除换行符。更有可能的情况是,当你将输入文本转换为ArrayList
时,换行符已被删除。
但这是无关紧要的。如果你想要输出一个文本文件,不要使用ObjectOutputStream
。使用FileWriter
,并迭代ArrayList
以输出每一行,然后加上换行符。
> 当我将其作为ArrayList
读入时,我会丢失*[换行符]*吗?
这取决于你如何读取输入文件并填充ArrayList
。(如果你不向我们展示代码,我们无法解释你的代码行为。我们甚至不确定ArrayList
的元素类型是什么...)
英文:
You have misunderstood the tutorial. ObjectOutputStream
is not designed for outputting text files. If you try to read a file produced by this class, you will see lots of binary data; i.e. things that show up as unprintable characters or "garbage" if you try to view it as text.
However, ObjectOutputStream
it will not be explicitly removing line breaks. It is more likely that the line break characters were removed when you turned your input text into an ArrayList
.
But that is moot. If you want to output a text file, don't use ObjectOutputStream
. Use a FileWriter
and iterate the ArrayList
to output each (erm) line followed by a line break.
> Do I lose [the line breaks] when I read it in as ArrayList
?
That depends on how your read the input file and populated the ArrayList
. (We cannot explain the behavior of your code if you don't show it to us. We don't even know for sure what the element type for the ArrayList
is ...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论