在JAR文件中,URL getResource不起作用 [英] URL getResource not working when in JAR file
问题描述
我的应用程序加载了一个txt文件,该文件位于 PROJECTNAME / resource
文件夹中。
My application loads a txt file which is in PROJECTNAME/resource
folder.
以下是我加载文件的方式:
Here is how I'm loading the file:
URL url = getClass().getClassLoader().getResource("batTemplate.txt");
java.nio.file.Path resPath;
String bat = "";
try {
resPath = java.nio.file.Paths.get(url.toURI());
bat = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
} catch (URISyntaxException | IOException e1) {
e1.printStackTrace();
}
注意:当我从Eclipse运行时这是有效的,当我导出到Jar文件(将生成的JAR中提取所需的lib。)时,不会。
我知道该文件正在被提取,因为它在JAR文件中。图像也有效。
NOTE: This works when I run from Eclipse, and doesn't when I Export to a Jar file (Extract required lib. into generated JAR). I know that the file is being extracted because its in the JAR file. Also the images work.
错误MSG:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Illegal character in path at index 38: file:/C:/DataTransformation/Reports Program/ReportsSetup.jar
at com.sun.nio.zipfs.ZipFileSystemProvider.uriToPath(ZipFileSystemProvider.java:87)
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:166)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
at java.nio.file.Paths.get(Unknown Source)
at ReportSetup$13.mouseReleased(ReportSetup.java:794)
我也是看看这里的类似问题,但是它们引用了JAR文件之外的文件/ URL。
I also looked at the similar problem here, however they refer to file/URL outside JAR file.
推荐答案
.jar条目不是文件;它是.jar存档的一部分。无法将资源转换为Path。你需要使用 getResourceAsStream
来阅读它。
A .jar entry is not a file; it is part of the .jar archive. It is not possible to convert a resource to Path. You’ll want to read it using getResourceAsStream
instead.
要阅读所有内容,你有几个选择。您可以使用扫描仪:
To read all of it, you have a few options. You can use a Scanner:
try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
bat = s.useDelimiter("\\Z").next();
if (s.ioException() != null) {
throw s.ioException();
}
}
您可以将资源复制到临时文件:
You can copy the resource to a temporary file:
Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
Files.copy(stream, batFile);
}
您只需从InputStreamReader中读取文本:
You can simply read the text from an InputStreamReader:
StringBuilder text = new StringBuilder();
try (Reader reader = new BufferedReader(
new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("batTemplate.txt"),
StandardCharsets.UTF_8))) {
int c;
while ((c = reader.read()) >= 0) {
text.append(c);
}
}
String bat = text.toString();
这篇关于在JAR文件中,URL getResource不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!