尝试读取文件时出现奇怪的NoSuchFileException

时间:2019-04-05 13:12:48

标签: java resources

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

成功给了我一个keyFile。如果我现在用以下方式列出路径:

privateKeyFile.toPath()

调试成功地向我显示了文件的路径:

  

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

-

但是,一旦我尝试使用读取该文件

Files.readAllBytes(privateKeyFile.toPath())

我明白了

  

方法引发了“ java.nio.file.NoSuchFileException”异常。

这真的很令人困惑,我已经尝试将getResource()更改为getResource("/privateKey");之类的各种东西-但这很快就会出错,实际上是在尝试创建{{1} },因此该文件必须如我上面显示的那样存在??

3 个答案:

答案 0 :(得分:0)

感谢您的回复,我现在可以成功使用此代码

AutoMapperMappingException

我最初尝试了给定的另一种方法,但是导致BadPaddingException,可能是由于未完全读取文件

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

答案 1 :(得分:-1)

ctime的构造函数并不关心路径字符串是否实际指向现有文件,因此请不要依赖于它来检查文件是否存在。请改用File(如果文件存在,则返回privateKeyFile.exists())。从我看来,该文件确实不存在或您提供的路径不正确,因此true应该返回false。

答案 2 :(得分:-3)

由于该文件位于您的Jar内,因此Java无法将其识别为实际的“文件”。因此,您必须阅读一些不同的内容。根据{{​​3}}的说法,您可能会这样阅读:

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

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

或者您使用Java 9+,可能看起来像这样:

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

编辑: 由于某些人想要一个包含read函数的整个源代码的示例,因此您可以进行以下操作:

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();