Is Java. Nio. File. Files. newInputStream(myfile. toPath()) Better Than New Fileinputstream(File)?

I was using soanr to check my java code, and one issue shows that ,we should use java.nio.file.Files.newInputStream(myfile.toPath()) instead of new FileInputStream(file). And the sonar description is :

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());

My question is, is it right?

1

1 Answer

That is a dense statement. Thus, it might be worth to break it into smaller chunk. First thing first,

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

This is true and false. the function itself has been marked as deprecated since java 9. And, it has been removed 5 months ago. So, depending on java version you used. It probably still exists (assuming most people are still using java 8). See this commit for more information.

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

Yeah, because, finalize function is invoked after GC. Then, most likely, the object would linger on the heap longer. See javadoc for finalize function here.

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

True, I have checked the source code in openjdk repo. And, I don't see the implementation of classes that those two functions use implement the finalize method. See the repo here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest