简体   繁体   English

用getResourceAsStream替换FileInputStream

[英]Replacing FileInputStream with getResourceAsStream

I am currently reading in a public key file using the following code: 我目前正在使用以下代码读取公共密钥文件:

    // Read Public Key.
    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

However, I wish to include the key files in with my jar. 但是,我希望将密钥文件包含在我的jar中。 I have dragged the key files into my project in eclipse and I am trying to load the public key using the following to replace what is above: 我已将密钥文件拖到eclipse中的项目中,并尝试使用以下内容加载公钥以替换上面的内容:

    InputStream is = getClass().getResourceAsStream( "/RSAAlgorithm2/public.key" );
    byte[] encodedPublicKey = new byte[(int) 2375];
    is.read(encodedPublicKey);
    is.close();

However I keep getting a NullPointerException. 但是我一直收到NullPointerException。

java.lang.NullPointerException at RSA.LoadKeyPair(RSA.java:122) at RSA.main(RSA.java:31) RSA.main(RSA.java:31)处RSA.LoadKeyPair(RSA.java:122)处的java.lang.NullPointerException

Is this because I am incorrectly loading in the file? 这是因为我没有正确加载文件吗? Can files be dragged into eclipse and loaded like this or is it a requirement to have them seperate from the JAR? 可以像这样将文件拖入eclipse并加载吗,还是需要将它们与JAR分开?

Check if is is null after doing getResourceAsStream . 在执行getResourceAsStream之后,检查是否is null If it is, the resource has not been found. 如果是,则找不到资源。 In this case check the path to the file, it is relative to your classpath. 在这种情况下,请检查文件的路径,它是相对于您的类路径的。 I don't know your project setup but I would try to simply use "/public.key" 我不知道您的项目设置,但我会尝试简单地使用"/public.key"

With this name, you have to put the "public.key" file in the RSAAlgorithm2 package. 使用此名称,您必须将“ public.key”文件放入RSAAlgorithm2包中。 That means in your "jar" file, you should see an entry named "RSAAlgorithm2/public.key". 这意味着在“ jar”文件中,您应该看到一个名为“ RSAAlgorithm2 / public.key”的条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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