【发布时间】:2017-06-09 09:40:37
【问题描述】:
我在为我的应用程序创建可执行 jar 时遇到问题,我无法读取位于资源文件夹中的任何文件。 资源文件位于:src > main > resources。
我有一个 .xml 配置文件和 log4j.properties 文件。
当我从 Eclipse 中运行应用程序时,一切正常(读取 xml 并创建日志文件)但是当我将其部署为可执行 jar 时突然不再写入日志文件并且 classLoader.getResource(xmlFile) 返回空。
知道如何解决这个问题吗?
这是我使用的一段代码: 参数 xmlFile 就是 'readMe.xml' 等文件名
private Document xmlDocument (String xmlFile) throws ParserConfigurationException, SAXException, IOException{
// return null if the file is not an xml file
System.out.println(" - xmlFile : " + xmlFile);
if(! xmlFile.substring(xmlFile.lastIndexOf(".") + 1).toLowerCase().equals("xml") ){
return null;
}
//Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Build Document
ClassLoader classLoader = getClass().getClassLoader();
URL res = classLoader.getResource( xmlFile);
System.out.println(" - res : " + res);
File file = new File( classLoader.getResource( xmlFile).getFile() );
if (file == null){
System.out.println(" - xmlDocument - OUT");
return null;
}
Document document = builder.parse(new File(classLoader.getResource(xmlFile).getFile()));
//Normalise the XML Structure;
System.out.println(" - xmlDocument 5 - before normalizing document");
document.getDocumentElement().normalize();
return document;
}
【问题讨论】:
-
现在所有东西都在罐子里了吗? jar 中的对象不是文件,您不能使用
File访问它们。看getResourceAsStream。 -
您是否检查过您的 .jar 文件是否包含
readMe.xml条目?您可以在 IDE 中检查 .jar 文件的内容,也可以使用每个 JDK 附带的jar工具,或者您可以复制它并将副本的扩展名更改为.zip,然后使用任何 zip 工具检查文件(因为每个 .jar 文件实际上都是一个 zip 文件)。请注意,URL.getFile() 不会将 URL 转换为有效的文件名。根本不要尝试将您的 URL 转换为文件。请改用try (InputStream file = classLoader.getResourceAsStream(xmlFile)) { document = builder.parse(file); }。
标签: java eclipse deployment nullpointerexception resources