包中的文件不会从java应用程序中打开。

318 阅读1分钟

亲爱的专家们,这个问题与

  • 文件在java中不打开,后者位于jar文件中。

更新问题

我用了两个密码

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"。我使用了以下代码同一页我的PdfReaderAdobe阅读器显示异常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文件,它运行良好。但没有在PDF和DOC。主要问题是当我运行应用程序更改项目工作空间目录时。实际上我想做的是:Ntebeans键盘-下面的短代码文档Help菜单

一个罐子是一个压缩档案。所以首先来看看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);
}