gpt4 book ai didi

java - java.nio.file.Files.newInputStream(myfile.toPath()) 比 new FileInputStream(file) 更好吗?

转载 作者:行者123 更新时间:2023-11-30 05:42:48 25 4
gpt4 key购买 nike

我正在使用 soanr 来检查我的 java 代码,有一个问题表明,我们应该使用 java.nio.file.Files.newInputStream(myfile.toPath()) 而不是 new FileInputStream(file)。声纳描述是:

This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method, which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected. Java 7 introduced two ways to create streams for reading and writing files that do not have this concern. You should consider switching from these above classes to InputStream is = java.nio.file.Files.newInputStream(myfile.toPath()); OutputStream os = java.nio.file.Files.newOutputStream(myfile.toPath());

我的问题是,这样对吗?

最佳答案

这是一个密集的陈述。因此,将其分成更小的 block 可能是值得的。首先,

This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method

这是真的,也是假的。该函数本身自 java 9 起已被标记为已弃用。并且它已在 5 个月前被删除。所以,取决于你使用的java版本。它可能仍然存在(假设大多数人仍在使用 java 8)。看这个commit了解更多信息。

which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected

是的,因为finalize函数是在GC之后调用的。然后,该对象很可能会在堆上停留更长时间。请参阅 javadoc 了解 finalize 函数 here .

Java 7 introduced two ways to create streams for reading and writing files that do not have this concern

确实,我已经检查了 openjdk repo 中的源代码。而且,我没有看到这两个函数使用的类的实现来实现 Finalize 方法。请参阅存储库 here

关于java - java.nio.file.Files.newInputStream(myfile.toPath()) 比 new FileInputStream(file) 更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55370117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com