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

标签 java jar classloader archive embedded-resource

注意:这是我的问题 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/

相关文章:

java - java中的正则表达式命令

java - 实例方法是按对象还是按类加载到内存中?

gradle - 如何将javascript依赖项打包到Kotlin JS项目JAR中?

java - Visual Studio 代码,Java 扩展,如何将 JAR 添加到类路径?

java - 如何将我的自定义类加载器设置为默认?

java - 使用引用编译动态加载的类

java - Gremlin 查询的 Union 方法的使用及其对 Neptune 交易的影响

Java NTP 客户端

java - 我该怎么做才能使 jar /类更小?

java - 从 lib 目录加载 jar 文件的顺序