从Web应用程序中的jar文件读取
问题描述:
我有一个独立的应用程序,我将其作为JAR文件导出,将其包含在运行于Tomcat的Web应用程序中。从Web应用程序中的jar文件读取
的独立应用程序从一个文件,该文件是包“配置”里面读取,通过这条线:
configFileName = Thread.currentThread().getContextClassLoader().getResource("config/indexer.cfg").getPath();
不幸的是这将导致在web应用程序的异常:
java.io.FileNotFoundException: file:\C:\apache-tomcat-7.0.23\IRSimWebApp\WEB-INF\lib\IR_Sim.jar!\config\indexer.cfg (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
我注意到文件路径中有一个感叹号。这可能导致错误?它是如何到达那里的?
答
好像你会通过获取资源为InputStream
得到更好的服务:
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/indexer.cfg");
if (in != null) {
BufferedInputStream buff = new BufferedInputStream(in);
// process buff to get contents of file
buff.close();
}
没有异常处理上面,很明显,但你应该明白我的意思...
我想,是什么你所做的是正确的。 exlclamation意味着它位于JAR内部。 – 2013-02-20 17:08:36
该行不可能导致给定的异常。你是不是错误地在代码中进一步下了新的FileInputStream(configFileName)?这将符合例外。 – BalusC 2013-02-20 18:40:44
是的,它是由代码后面的一个新的FileInputStream引起的 – PogoMips 2013-02-20 18:46:21