Java Jar 文件:使用资源错误:URI 不分层 [英] Java Jar file: use resource errors: URI is not hierarchical

查看:36
本文介绍了Java Jar 文件:使用资源错误:URI 不分层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have deployed my app to jar file. When I need to copy data from one file of resource to outside of jar file, I do this code:

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 hierarchy.这个错误我在 IDE 中运行时没有遇到.

The error I have met is: URI is not hierarchical. this error I don't meet when run in IDE.

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

If I change above code as some help on other post on 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
  //....
}

推荐答案

你不能这样做

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

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

it is not a file! When you run from the ide you don't have any error, because you don't run a jar file. In the IDE classes and resources are extracted on the file system.

但是你可以这样打开一个InputStream:

But you can open an InputStream in this way:

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

删除/resource".通常,IDE 将文件系统类和资源分开.但是当 jar 被创建时,它们被放在一起.所以文件夹级别的"/resource"仅用于类和资源分离.

Remove "/resource". Generally the IDEs separates on file system classes and resources. But when the jar is created they are put all together. So the folder level "/resource" is used only for classes and resources separation.

当你从类加载器中获取资源时,你必须指定资源在 jar 中的路径,这就是真正的包层次结构.

When you get a resource from classloader you have to specify the path that the resource has inside the jar, that is the real package hierarchy.

这篇关于Java Jar 文件:使用资源错误:URI 不分层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆