0

I am trying to refer to a file inside a maven project structure. Through my test cases the file is located successfully, but when I deploy the project to a weblogic environment, I am receiving an error:

java.io.FileNotFoundException: keystore.jks (The system cannot find the path specified)

In my code I am referring to the file as follow:

File pKeyFile = new File("certificates/keystore.jks");
String pKeyPassword = keyStorePassword;
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyInput = new FileInputStream(pKeyFile);

Update:

I tried the following:

File pKeyFile = new File(this.getClass().getClassLoader().getResourceAsStream("certificates/keystore.jks").toString());
        String pKeyPassword = keyStorePassword;
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyInput = new FileInputStream(pKeyFile);
        keyStore.load(keyInput, pKeyPassword.toCharArray());
        keyInput.close();
        keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

When I evaluated the this.getClass().getClassLoader().getResourceAsStream("certificates/keystore.jks") expression, I could see that the file was found. But it still threw the same error when it tried to load the file as an InputStream.

Hendrien
  • 325
  • 1
  • 10
  • 20
  • 1
    You should use "certificates/keystore.jks" – pkgajulapalli Mar 11 '18 at 15:24
  • My apologies. That was just a test I ran, I updated the question. – Hendrien Mar 11 '18 at 15:36
  • 1
    Take a look on this page: https://www.mkyong.com/java/java-read-a-file-from-resources-folder/. You should use something like `File file = new File(classLoader.getResource(fileName).getFile());` where class loader is `ClassLoader classLoader = getClass().getClassLoader();` – Michał Ziober Mar 11 '18 at 16:18
  • Hi @MichałZiober I am using the ClassLoader example and I can see that the file is retrieved, but when I load it into a FileInputStream it still returns the same error, do you perhaps have any ideas ? – Hendrien Mar 12 '18 at 08:19

1 Answers1

0

You cannot write

File pKeyFile = new File("src/main/resources/certificates/keystore.jks");

In Java paths are either:

  1. Absolute
  2. Relative: that's your case
  3. Classpath resources

A relative path starts from the location where your program is run. So using src/ is definitely wrong

David Brossard
  • 13,584
  • 6
  • 55
  • 88
  • Do you perhaps know how I can use the file using classpath resources ? I see the file is generated under target/classes/certificates/keystore.jks – Hendrien Mar 11 '18 at 15:38
  • Have a look at https://stackoverflow.com/questions/793213/getting-the-inputstream-from-a-classpath-resource-xml-file – David Brossard Mar 11 '18 at 17:06