I am facing issues with one of my application, and encountered the following exception when handling large amount of transaction that involves opening file and reading the content:
java.io.FileNotFoundException: /keystore-sample/keystore.jks (Too many open files)
I have the following sample code written in java:
try {
EncryptDecryptPassword crypt = new EncryptDecryptPassword();
String secretKey = "secret123";
String trustpassencrypted = "ecnrypted1234";
String trustpass = crypt.decryptPassword(trustpassencrypted.trim(), secretKey.trim());
File truststore = new File("/keystore-sample/keystore.jks");
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(truststore), trustpass.toCharArray());
//Continue with the rest of the code...
} catch (KeyStoreException kse) {
System.out.println("Security configuration failed with the following: " + kse.getCause());
} catch (NoSuchAlgorithmException nsa) {
System.out.println("Security configuration failed with the following: " + nsa.getCause());
} catch (FileNotFoundException fnfe) {
System.out.println("Security configuration failed with the following: " + fnfe.getCause());
} catch (UnrecoverableKeyException uke) {
System.out.println("Security configuration failed with the following: " + uke.getCause());
} catch (CertificateException ce) {
System.out.println("Security configuration failed with the following: " + ce.getCause());
}catch (IOException ioe) {
System.out.println("Security configuration failed with the following: " + ioe.getCause());
}
As you can see, i did not declare a new instance for FileInput stream, like the following:
Correction : My intention is to express that i did not assign the newly created FileInputStream into a variable and manually close it later, like the following :
FileInputStream in = new FileInputStream(truststore);
keyStore.load(in, trustpass.toCharArray());
//once done with the input stream, close it
in.close();
My question is : will new FileInputStream(truststore) actually requires manual closing or it will be handled by the underlying Keystore class? Quick glance on the underlying decompiled code of Keystore.class, i don't see that. Just to confirm if this is the particular reason why i am hitting the exception.
Also, is the code implementation above considered as bad practice ?
EDIT:
Due to some restriction on application environment i am running, this is using old Java SE 6u34.