-1

亲爱的专家,这个问题与

更新的问题

我使用了两个代码:

如果我从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". 我使用了来自同一页面的以下代码,我的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文件,它工作正常。但不能在PDFand中工作DOC。主要问题是当我运行应用程序更改项目工作空间目录时。其实我想做这样的: 菜单下的Ntebeans键盘短代码文档Help

4

2 回答 2

1

jar 是一个 zip 存档。所以先用7zip/WinZip之类的看看。检查其中的路径是否确实resources/User_Guide.pdf(区分大小写!)。它很可能/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);
}
于 2013-09-26T09:12:09.010 回答
0

我没有足够的声誉来评论 Joop Eggen 接受的答案,但是这条线

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

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

InputStream in = getClass().getResourceAsStream("/resources/User_Guide.pdf");
于 2017-06-06T15:37:20.133 回答