gpt4 book ai didi

java - 无法从外部 Jar 文件检索资源

转载 作者:行者123 更新时间:2023-12-01 15:20:01 24 4
gpt4 key购买 nike

注意:这是我的问题 here. 的后续问题

<小时/>

我有一个程序,它获取目录的内容并将所有内容捆绑到 JAR 文件中。我用来执行此操作的代码在这里:

    try
{
FileOutputStream stream = new FileOutputStream(target);
JarOutputStream jOS = new JarOutputStream(stream);

LinkedList<File> fileList = new LinkedList<File>();
buildList(directory, fileList);

JarEntry jarAdd;

String basePath = directory.getAbsolutePath();
byte[] buffer = new byte[4096];
for(File file : fileList)
{
String path = file.getPath().substring(basePath.length() + 1);
path.replaceAll("\\\\", "/");
jarAdd = new JarEntry(path);
jarAdd.setTime(file.lastModified());
jOS.putNextEntry(jarAdd);

FileInputStream in = new FileInputStream(file);
while(true)
{
int nRead = in.read(buffer, 0, buffer.length);
if(nRead <= 0)
break;
jOS.write(buffer, 0, nRead);
}
in.close();
}
jOS.close();
stream.close();

所以,一切都很好,jar 已创建,当我使用 7-zip 探索其内容时,它包含了我需要的所有文件。但是,当我尝试通过 URLClassLoader 访问 Jar 的内容时(该 jar 不在类路径上,而且我不希望如此),我得到了空指针异常。

奇怪的是,当我使用从 Eclipse 导出的 Jar 时,我可以按照我想要的方式访问它的内容。这让我相信我没有正确创建 Jar,并且遗漏了一些东西。上面的方法有没有遗漏什么?

最佳答案

我根据 this question 计算出来的- 问题是我没有正确处理反斜杠。

固定代码在这里:

        FileOutputStream stream = new FileOutputStream(target);
JarOutputStream jOS = new JarOutputStream(stream);

LinkedList<File> fileList = new LinkedList<File>();
buildList(directory, fileList);

JarEntry entry;

String basePath = directory.getAbsolutePath();
byte[] buffer = new byte[4096];
for(File file : fileList)
{
String path = file.getPath().substring(basePath.length() + 1);
path = path.replace("\\", "/");
entry = new JarEntry(path);
entry.setTime(file.lastModified());
jOS.putNextEntry(entry);
FileInputStream in = new FileInputStream(file);
while(true)
{
int nRead = in.read(buffer, 0, buffer.length);
if(nRead <= 0)
break;
jOS.write(buffer, 0, nRead);
}
in.close();
jOS.closeEntry();
}
jOS.close();
stream.close();

关于java - 无法从外部 Jar 文件检索资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066773/

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