Java Jar文件:使用资源错误:URI不是分层的

时间:2012-04-13 15:54:36

标签: java deployment resources executable-jar

我已将我的应用程序部署到jar文件。当我需要将数据从一个资源文件复制到jar文件之外时,我执行以下代码:

URL resourceUrl = getClass().getResource("/resource/data.sav");
File src = new File(resourceUrl.toURI()); //ERROR HERE
File dst = new File(CurrentPath()+"data.sav");  //CurrentPath: path of jar file don't include jar file name
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
 // some excute code here

我遇到的错误是:URI is not hierarchical。在IDE中运行时,我不满足此错误。

如果我更改上面的代码作为StackOverFlow上其他帖子的一些帮助:

InputStream in = Model.class.getClassLoader().getResourceAsStream("/resource/data.sav");
File dst = new File(CurrentPath() + "data.sav");
FileOutputStream out = new FileOutputStream(dst);
//....
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) { //NULL POINTER EXCEPTION
  //....
}

6 个答案:

答案 0 :(得分:86)

你不能这样做

File src = new File(resourceUrl.toURI()); //ERROR HERE

它不是文件! 当您从ide运行时,您没有任何错误,因为您没有运行jar文件。在IDE中,在文件系统中提取类和资源。

但你可以用这种方式打开InputStream

    InputStream in = Model.class.getClassLoader().getResourceAsStream("/data.sav");

删除"/resource"。通常,IDE会分离文件系统类和资源。但是当创建jar时,它们会被放在一起。因此文件夹级别"/resource"仅用于类和资源分离。

从类加载器获取资源时,必须指定资源在jar中的路径,即真正的包层次结构。

答案 1 :(得分:12)

如果由于某种原因你确实需要创建一个java.io.File对象来指向Jar文件中的资源,答案就在这里:https://stackoverflow.com/a/27149287/155167

File f = new File(getClass().getResource("/MyResource").toExternalForm());

答案 2 :(得分:8)

以下是Eclipse RCP / Plugin开发人员的解决方案:

Bundle bundle = Platform.getBundle("resource_from_some_plugin");
URL fileURL = bundle.getEntry("files/test.txt");
File file = null;
try {
   URL resolvedFileURL = FileLocator.toFileURL(fileURL);

   // We need to use the 3-arg constructor of URI in order to properly escape file system chars
   URI resolvedURI = new URI(resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null);
   File file = new File(resolvedURI);
} catch (URISyntaxException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
}

使用FileLocator.toFileURL(fileURL)而不是resolve(fileURL)非常重要 ,当插件被打包到jar中时,这将导致Eclipse在临时位置创建一个解压缩版本,以便可以使用File访问该对象。例如,我猜Lars Vogel在他的文章中有一个错误 - http://blog.vogella.com/2010/07/06/reading-resources-from-plugin/

答案 3 :(得分:0)

虽然我自己偶然发现了这个问题但我想添加另一个选项(来自@ dash1e的完美解释):

通过添加:

将插件导出为文件夹(而不是jar)
Eclipse-BundleShape: dir

MANIFEST.MF

至少当您使用导出向导(基于*.product)文件导出RCP应用程序时,这会得到尊重并生成一个文件夹。

答案 4 :(得分:0)

除了一般答案之外,你可以得到" URI不是分层的"从 Unitils 库尝试从.jar文件加载数据集。将数据集保存在一个maven子模块中,但在另一个maven子模块中保留实际测试时,可能会发生这种情况。

甚至有bug UNI-197提交。

答案 5 :(得分:0)

我之前遇到过类似的问题,并且我使用了代码:

new File(new URI(url.toString().replace(" ","%20")).getSchemeSpecificPart());

代替代码:

new File(new URI(url.toURI())

解决问题