【问题标题】:classLoader.getResource() works in Eclipse but returns null when deployedclassLoader.getResource() 在 Eclipse 中工作,但在部署时返回 null
【发布时间】: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


【解决方案1】:

您可能必须在类路径中指定资源,试试这个。

  1. 将您的类导出为普通 jar,而不是可执行 jar。
  2. 将所有资源复制到配置目录,例如 <base_paths>/config,并将 jar 复制到目录,例如 <base_paths>/lib
  3. 运行命令

在窗口中

java -cp <base_paths>/config;<base_paths>/lib/yourJar.jar com.xyz.YourMainclass

在 Unix 中

java -cp <base_paths>/config:<base_paths>/lib/yourJar.jar com.xyz.YourMainclass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 2017-10-15
    相关资源
    最近更新 更多