英文:
The consequences of not closing a PrintWriter object
问题
我编写了一个非常基本的程序,它接受两个等长的温度列表,并使用它们创建一个 .CSV 文件。奇怪的是,当我忘记关闭 PrintWriter 对象并运行程序时,输出文件会缺少大约 300 个结果(我不知道缺少了哪些结果),并且根据 println 中逗号的写入方式,无论是像这样写 ", " 还是像这样写 ",",它缺少的结果数量都不同。当我关闭 PrintWriter 时,无论逗号的写入方式如何,输出文件都会有正确数量的结果。我只是想知道是否有人能解释一下为什么会发生这种情况,我以为关闭 PrintWriter 只会像关闭 Scanner 对象一样将其关闭?
我现在无法访问代码,但只是一个 for 循环,它会以以下格式打印两个数组当前索引的值:
PrintWriter.println(list1.get[i] + "," + list2.get[i];
英文:
I wrote a really basic program which takes 2 equally sized lists of temperatures and creates a .CSV file using them. The weird part is that when I forgot to close the PrintWriter object and ran the program the output file was missing 300ish results (I don't know which results were missing) and depending on how the comma in the println was written either like this ", " or like this "," it would be missing a different number of results. When I closed the PrintWriter regardless of how the comma was written the output file would have the correct number of results. I was just wondering if anyone could explain why this was happening I thought closing the PrintWriter would just close it in the same was as closing a Scanner object would?
Don't have access to the code right now but it was just a for loop which would print the value of the current index of the 2 arrays in this format
PrintWriter.println(list1.get[i] + "," + list2.get[i];
答案1
得分: 1
除了写入内容没有被正确刷新,从而部分丢失之外,每个打开的写入器都会占用资源(RAM 和操作系统文件句柄),并且还会阻止其他进程访问该文件。
在使用完毕后,请始终关闭每个写入器和阅读器。
英文:
Aside from the writer content not being properly flushed and thus getting partially lost, every open writer hogs resources (RAM and OS file handles), and also blocks the file from being accessed by other processes.
Always close every writer and reader once you're done with it.
答案2
得分: 1
通常,输出会在内存中收集,并且只会不时地写入磁盘。这样做是因为较大的磁盘写入更加高效。
当您不关闭写入器时,会错过最后一个装满输出的缓冲区。但还有其他负面影响,文件将保持打开状态,直到程序退出。如果您反复这样做,会导致资源泄漏。
英文:
Typically, output is collected in memory and only written to disk from time to time. This is done since larger disk writes are much more efficient.
When you don't close the writer you miss the last buffer full of output. But there are other negative consequences as well, the file will stay open until the program exits. If you do this repeatedly it will lead to resource leaks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论