gpt4 book ai didi

java - URL getResource 在 JAR 文件中时不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:38 36 4
gpt4 key购买 nike

我的应用程序加载了一个位于 PROJECTNAME/resource 文件夹中的 txt 文件。

enter image description here

这是我加载文件的方式:

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 中)时无效。我知道该文件正在被提取,因为它在 JAR 文件中。图像也有效。

enter image description here

错误信息:

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。

最佳答案

.jar 条目不是文件;它是 .jar 存档的一部分。无法将资源转换为路径。您需要改用 getResourceAsStream 来阅读它。

要阅读所有内容,您有几种选择。您可以使用扫描仪:

try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
bat = s.useDelimiter("\\Z").next();
if (s.ioException() != null) {
throw s.ioException();
}
}

您可以将资源复制到临时文件:

Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
Files.copy(stream, batFile);
}

您可以简单地从 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();

关于java - URL getResource 在 JAR 文件中时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39167762/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com