问题描述
这是我的代码:
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(new FileInputStream(TRUSTSTORE_FILE),TRUSTSTORE_PASSWORD.tochararray()); //sonarqube issue
哪个是最适合完成此操作的InputStream?
这是完整的错误:
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.
我真的需要切换到:
InputStream is = java.nio.file.Files.newInputStream(myfile.toPath());
我对此不满意。
解决方法
将其包装在try-with-resources中,以便在代码块末尾将其关闭。错误消息抱怨该文件可能已打开很长时间。
try (InputStream in = new FileInputStream(TRUSTSTORE_FILE)) {
KeyStore truststore = KeyStore.getInstance("JKS");
truststore.load(in,TRUSTSTORE_PASSWORD.toCharArray());
} // Automatically closes in.
这会释放系统资源(文件句柄),并允许其他人覆盖信任库文件。