簡體   English   中英

無法從外部jar文件檢索資源

[英]Can't Retrieve Resources from External Jar File

注意:這是我的問題的跟進


我有一個使用目錄內容並將所有內容捆綁到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,並遺漏了一些東西。 上面的方法有什么遺漏嗎?

我是根據這個問題弄清楚的-問題是我沒有正確處理反斜杠。

固定代碼在這里:

        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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM