英文:
In order to release memory, what can I do after new a File instance in Java?
问题
在某些情况下,我需要在Java中操作Word文档,通常我需要创建一个新的文件实例,就像:
File file = new File("路径/到/目标/文件");
在我使用完它后,是否需要做些什么来释放内存?
file = null;
似乎效果不太好。
英文:
In some case, I need to operator Doc file in Java, I usually need new a File instance, like:
File file = new File("path/to/target/file");
should I do somethine after I use it for release memory?
file = null;
seems not work well.
答案1
得分: 1
file = null;
[可能] 不会产生任何影响,只要你用于打开文件的流或读取器仍然存在,因为该流或读取器 [可能] 会持有对该 File
的引用。无论如何,在内存消耗的更大图景中,一个 File
实例基本上微不足道;如果一个 File
对象的持续存在与否会决定你的程序存亡,那几乎是不可能的。
尽管如此,在你不再需要该 File
实例时执行 file = null;
当然是没有害处的。但是,如果可用内存不立即增加几个字节,不要感到惊讶或担心!
英文:
file = null;
[probably] won't do anything as long as the stream or reader you used to open the file still exists because that stream or reader [probably] will hold a reference to that File
. And anyway, a File
is virtually nothing in the bigger picture of memory consumption; it's highly unlikely your program will live or die over the continued existence of a single File
object.
That said, there's certainly no harm in doing file = null;
when you have no further use for that File
instance. Just don't be either surprised or worried if the available memory doesn't instantly jump up by a few bytes!
答案2
得分: 1
首先,File
实例不仅仅是文件名。它的内存占用极小。
Java 拥有一个垃圾收集器,将负责回收未使用(不可访问)的对象。您无需在您的一侧执行任何特殊操作。
英文:
First, a File
instance is not much more than the file name. Its memory footprint is negligible.
Java has a garbage collector that will take care of reclaiming unused (unreachable) objects. There is no special action necessary on your side.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论