Do you need to explicity close a Java KeyStore input stream?

青春壹個敷衍的年華 提交于 2019-12-20 02:09:37

问题


When reading in a KeyStore using a FileInputStream as follows, does one need to explicitly close the input-steam to stop system resources being wasted ?

FileInputStream fin = new FileInputStream("keystore.jks");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fin, password);

//  Is this line needed ??
fin.close();

Is this FileInputStream closed automatically by the load() method or is explicit manually intervention required?


回答1:


Is this FileInputStream closed automatically by the load() method or is explicit manually intervention required?

yes it required to close to over come unnecessary leaks.

Checkout example given in java doc of KeyStore http://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.html




回答2:


Yes, try this test

    FileInputStream fin = new FileInputStream("keystore.jks") {
        public void close() throws java.io.IOException {
            System.out.println("close");
        }
    };
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(fin, "changeit".toCharArray());

and you will see that close() is not called




回答3:


You should definitly use org.apache.commons.io.IOUtils.closequietly when dealing with streams and APIs you are not sure about



来源:https://stackoverflow.com/questions/23891562/do-you-need-to-explicity-close-a-java-keystore-input-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!