简体   繁体   中英

Strange NoSuchFileException when trying to read a file

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

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

privateKeyFile.toPath()

debug successfully shows me a path to the file:

file:/Users/me/.m2/repository/com/xx/xyz/abc/encryption/1.0/encryption-1.0.jar!/privateKey

--

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

Files.readAllBytes(privateKeyFile.toPath())

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??

Thanks to replies, I now use this code successfully

//working
InputStream publicKeyStream = this.getClass().getClassLoader().getResourceAsStream("publicKey");
toByteArray(privateKeyStream));

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()];
in.read(array);

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.

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()];
in.read(array);

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()];
    in.read(b);
    bytes.addAll(b);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM