File privateKeyFile = new File(this.getClass().getClassLoader().getResource("privateKey").getFile());

successfully gives me a keyFile. If I now list the path with:


debug successfully shows me a path to the file:



However, as soon as I try and read that file with


I get

Method threw 'java.nio.file.NoSuchFileException' exception.

This is really confusing, and I've tried changing the getResource() to various things like getResource("/privateKey"); - yet that errors a lot sooner, actually a NPE right when trying to create a new File(), so the file MUST exist as I've shown above??

3 Answers

Wayneio On Best Solutions

Thanks to replies, I now use this code successfully

InputStream publicKeyStream = this.getClass().getClassLoader().getResourceAsStream("publicKey");

I initally tried the other method that was given, but that resulted in a BadPaddingException, likely due to not fully reading the file

//The incorrect code:

byte[] array = new byte[in.available()];;
Fishy On

Since the file is inside of your Jar, it is not recognized by Java as an actual "file". Because of this, you have to read it a little differently. According to this post, you might read it something like this:

InputStream in = getClass().getResourceAsStream("privatekey");

byte[] array = new byte[in.available()];;

Or of you're in Java 9+, it could look like this:

InputStream in = getClass().getResourceAsStream("privatekey"); 
byte[] array = in.readAllBytes();

Edit: Since some people wanted an example with the entire source code of the read function, here you go:

InputStream in = getClass().getResourceAsStream("privatekey"); 

List<Byte> bytes = new ArrayList<Byte>();
while(in.available() > 0) {
    byte[] b = new byte[in.available()];;

byte[] array = (byte[]) bytes.toArray();
Community On

The constructor of File does not care if the path string actually points to an existing file, so do not rely on that to check whether the file is there or not. Use privateKeyFile.exists() instead (it returns true if the file exists). From what I see, the file really isn't there or the path you give isn't correct, so exists() should return false.