英文:
Sonarqube - performance issue as Method uses a FileInputStream constructor, what are the better alternatives?
问题
这是我的代码:
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(new FileInputStream(TRUSTSTORE_FILE),
TRUSTSTORE_PASSWORD.toCharArray()); //sonarqube问题
哪种InputStream最适合完成这个任务?
这是完整的错误信息:
此方法创建并使用java.io.FileInputStream或java.io.FileOutputStream对象。不幸的是,这两个类都实现了finalize方法,这意味着创建的对象可能会一直存在,直到进行完整的垃圾回收,这将在堆上留下过多的垃圾,时间可能比预期的要长,甚至可能要长得多。
我真的需要切换到:
InputStream is = java.nio.file.Files.newInputStream(myfile.toPath());
我对这个不太满意。
英文:
Here is my code :
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(new FileInputStream(TRUSTSTORE_FILE),
TRUSTSTORE_PASSWORD.toCharArray()); //sonarqube issue
Which is the most suitable InputStream for getting this done?
Here is the full error :
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.
Do I really need to switch to :
InputStream is = java.nio.file.Files.newInputStream(myfile.toPath());
I am not comfortable with this one.
答案1
得分: 3
用try-with-resources将其包装起来,这样它将在代码块结束时被关闭。错误消息在抱怨文件可能已经打开了很长时间。
try (InputStream in = new FileInputStream(TRUSTSTORE_FILE)) {
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(in, TRUSTSTORE_PASSWORD.toCharArray());
} // 自动关闭。
这将释放系统资源(文件句柄),并允许其他操作覆盖信任存储文件。
<details>
<summary>英文:</summary>
Wrap it in a try-with-resources so it will be closed at the end of the block. The error message is complaining that the file might be open a long time.
try (InputStream in = new FileInputStream(TRUSTSTORE_FILE)) {
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(in, TRUSTSTORE_PASSWORD.toCharArray());
} // Automatically closes in.
This frees system resources (a file handle) and allows others to overwrite the truststore file.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论