我需要将密钥库路径作为库构造函数参数的一部分传递给第三方库。我将keystore(samplecerts)保存在类路径(src / main / resources)
中我刚刚添加以下行以进行测试,以查看文件是否真的被加载以及我是否正在向第三方发送正确的路径
InputStream in = new FileInputStream(path);
遵循两种方法 -
方法1:获取绝对路径 -
URL url = MyTest.class.getClassLoader().getResource("samplecerts");
String path = url.getPath();
System.out.println("Cert File Path:" +path);
InputStream in = new FileInputStream(path);
得到以下错误
/usr/local/java/bin/java -cp my-jar-with-dependencies.jar com.sample.MyTest
Cert File Path:file:/home/abc/my-jar-with-dependencies.jar!/samplecerts
Exception in thread "main" java.io.FileNotFoundException: file:/home/abc/my-jar-with-dependencies.jar!/samplecerts (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.sample.MyTest.main(MyTest.java:33)
方法2:在(src / main / resources /)下给出classpath中的文件名
String path = "samplecerts";
System.out.println("Cert File Path:" +path);
InputStream in = new FileInputStream(path);
得到以下错误 -
/usr/local/java/bin/java -cp my-jar-with-dependencies.jar com.sample.MyTest
Cert File Path:samplecerts
Exception in thread "main" java.io.FileNotFoundException: samplestore (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.sample.MyTest.main(MyTest.java:33)
在eclipse中,如果以java程序运行,它可以正常工作。这些错误可能是什么原因以及如何使其发挥作用?
答案 0 :(得分:0)
例如,如果您的样本位于jar内的/org/whatever/security/
下,那么您可以像这样加载它:
final String myPath = "/org/whatever/security/samplecerts";
InputStream myCerts = getClass().getResourceAsStream(myPath);