[英]can't find the resource which is in classpath while running the jar
我需要将密钥库路径作为库构造函数参数的一部分传递给第三方库。 我将密钥库(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程序运行,则可以正常工作。 这些错误的原因可能是什么,以及如何使其起作用?
例如,如果您的samplecerts位于jar的/org/whatever/security/
,则可以这样加载它:
final String myPath = "/org/whatever/security/samplecerts";
InputStream myCerts = getClass().getResourceAsStream(myPath);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.