为了释放内存,在Java中使用new创建一个File实例后,可以进行以下操作:

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月16日 11:22:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64382486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定