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

时间:2012-06-16 20:25:40

标签: 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,并且正在留下一些东西。上面的方法有什么遗漏吗?

1 个答案:

答案 0 :(得分:1)

我根据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();
相关问题