【问题标题】:How to create a file by using path string of this file which is in jar?如何使用 jar 中此文件的路径字符串创建文件?
【发布时间】:2019-06-19 08:08:21
【问题描述】:

我使用这个模式用 eclipse 创建了一个应用程序:

  • 应用程序
        • a.java
    • 资源
      • xmls
        • b.xml

在 a.java 中,我使用以下代码创建并使用一个文件:

File file = new File("resources/xmls/b.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);

此代码在 Eclipse 中运行良好,但是当我创建可运行的 jar 时,我收到此错误(我使用命令提示符运行此文件):

java.io.FileNotFoundException: D:\PROJECTS\App\build\dist\resources\xmls\b.xml (The system cannot find the path specified)
...

jar 文件位置是

D:\PROJECTS\App\build\dist  

它似乎试图在jar所在的目录中找到资源文件夹。 我的问题,如何将此 b.xml 文件路径字符串作为可运行 jar 的 File 的参数?

【问题讨论】:

  • 是的,我试过了,但它不起作用,同样的错误。
  • 假设你用java -jar app.jar path/to/file.xml 运行它,你会用File xmlFile = new File(args[0]); 得到这个参数。您也可以使用绝对路径。相对的将相对于您的.jar
  • 在jar文件中,有两个文件夹:package文件夹和xmls文件夹
  • 我只使用 java -jar app.jar

标签: java file path resources


【解决方案1】:

您可以使用 ClassLoader 类的public URL getResource(String name) 方法:

查找具有给定名称的资源。资源是一些数据 (图像、音频、文本等)可以通过类代码以某种方式访问 这与代码的位置无关。一个名字 resource 是一个以“/”分隔的路径名,用于标识资源。 此方法将首先在父类加载器中搜索 资源;如果 parent 为 null,则内置类加载器的路径 搜索到虚拟机。失败了,这个方法会 调用 findResource(String) 来查找资源。

所以您的代码将如下所示:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("xmls/b.xml").getFile());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
document.getDocumentElement().normalize();
//System.out.println("####Root element : " + document.getDocumentElement().getNodeName());

编辑

我创建了一个与您相同的结构,其中包含一个 xml 示例文件

<?xml version="1.0"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

在打印输出中我得到:#### 根元素:note,如果你愿意,我可以与你分享代码。无论如何,请确保您对您的空间有权限,并且您的路径将被格式化! (我用的是linux机器,没有windows没问题:D!)

【讨论】:

  • 我收到此错误:D:\PROJECTS\build\dist\file:\D:\PROJECTS\build\dist\App.jar!\xmls\b.xml (The filename, directory name, or volume label syntax is incorrect)
  • 我的资源不在src文件夹中
猜你喜欢
  • 2016-11-09
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2018-03-08
  • 1970-01-01
相关资源
最近更新 更多