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

标签 java

我正在使用 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/

相关文章:

RedHat Linux 中的 Java/Tomcat 内存泄漏?

java - 如何将ArrayList打印成行和列?

java - 如何模拟UUID?

java - Apache Ignite 作为多个数据库或其他持久性的统一外观

java - 为什么Jsoup遇到标签丢失不报错?

java - 尝试添加两个 float 时可能出现有损转换错误?

java - 如何在java中以 block 的形式从web服务返回数据

java - Java 中的局部变量 + lambda 函数出错

java - 当向 JTextArea 输入大量文本时,JTextFields 和 JTextArea 会缩小

java - CardLayout:如何在一个类中的ActionListeners中显示另一类中的面板?