包内的文件,不是从java应用程序打开的

时间:2013-09-26 08:48:47

标签: java file pdf file-io

亲爱的专家,这个问题与

有关

更新问题

我使用了两个代码:

如果我从workspace运行应用程序,以下代码可以正常工作。

URL resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");  
            File userGuideFile = null;  
            try {  
                userGuideFile = new File(resource.getPath());  
                if (Desktop.isDesktopSupported())  
                {  
                    Desktop desktop = Desktop.getDesktop();  
                    desktop.open(userGuideFile);  
                }  
            } catch (Exception e1) {  
                e1.printStackTrace();  
            }  

但如果我将project.jar复制到其他位置,则无法打开文件,并在我的日志中显示为file is not found "c:\workspace\project...pdf"。我使用了same page中的以下代码,我的 pdfReader adobe reader显示异常file is either not supproted or damaged

代码:

if (Desktop.isDesktopSupported())     
{     
    Desktop desktop = Desktop.getDesktop();     
    InputStream resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");  
try  
{  
    File file = File.createTempFile("User_Guide", ".pdf");  
    file.deleteOnExit();  
    OutputStream out = new FileOutputStream(file);  
    try  
    {  
        // copy contents from resource to out  
    }  
    finally  
    {  
        out.close();  
    }  
    desktop.open(file);     
}     
finally  
{  
    resource.close();  
}  
}  

请给我一些想法。我们将不胜感激。谢谢

注意:我尝试打开*.txt文件,但工作正常。但是没有在PDFDOC中工作。主要问题是当我运行应用程序更改项目工作空间目录时。其实我想做的是: Ntebeans键盘短代码文档,位于Help菜单

2 个答案:

答案 0 :(得分:1)

jar是一个zip存档。所以首先用7zip / WinZip等来看一下。 检查其中的路径确实是resources/User_Guide.pdf(区分大小写!)。 它可能是jar中的/User_Guide.pdf

无法立即从资源中获取文件(=文件系统上的文件)(只是偶然)。所以得到一个InputStream

InputStream in = getClass().getResource("/resources/User_Guide.pdf");
找不到时

NullPointerException。使用getClass时,类必须位于同一个jar中,并且此例中的路径以/开头。

现在您可以将输入流复制到某个临时文件,然后打开它。在Java 7中:

File file = File.createTempFile("User_Guide", ".pdf");  
Files.copy(in, file.toPath());

如果在Files.copy行中收到FileAlreadyExistsException,则添加以下CopyOption:

Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);

对于java< 7:

// copy contents from resource to out
byte[] buf = new byte[4096];
while ((int nread = in.read(buf, 0, buf.length)) > 0) {
    out.write(buf, 0, nread);
}

答案 1 :(得分:0)

我没有足够的声誉评论Joop Eggen的接受答案,但该行

InputStream in = getClass().getResource("/resources/User_Guide.pdf");

抛出错误"不兼容的类型:URL无法转换为InputStream"。而是使用方法getResourceAsStream():

InputStream in = getClass().getResourceAsStream("/resources/User_Guide.pdf");