我有一个Spring / Maven项目,在资源中有一些txt文件。 如果我在Eclipse下启动项目-应用程序可以正常运行,但是当我将其导出到jar中并尝试像这样启动时
java -j jar app.jar
我收到类似->
的错误java.io.FileNotFoundException: class path resource [AccessKey.key] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
at raceserver.Key.readFile(Key.java:61)
at raceserver.Key.setKey(Key.java:51)
at raceserver.Key.<init>(Key.java:22)
at raceserver.RaceServerApplication.<clinit>(RaceServerApplication.java:15)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
或:
2018-10-10 14:19:14.249 WARN 8820 --- [ main] .i.s.PathMatchingResourcePatternResolver : Cannot search for matching files underneath URL [rsrc:raceserver/] because it does not correspond to a directory in the file system
java.io.FileNotFoundException:URL [rsrc:raceserver /]无法解析为绝对文件路径,因为它不驻留在文件系统中:rsrc:raceserver /
这是我在代码中获取路径的方式:
private String serverKey = "";
private final String KEY_FILE = "AccessKey.key";
private void setKey() {
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {});
Resource resource = appContext.getResource(KEY_FILE);
((ClassPathXmlApplicationContext) appContext).close();
serverKey = readFile(resource);
}
private String readFile (Resource resource) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"));
while ((line = br.readLine()) != null) { sb.append(line); }
}
catch (IOException e) { e.printStackTrace(); }
finally {if(br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); }}
return sb.toString();
}
看来Eclipse并未将环境变量放在jar中...
请帮助提供好主意。