您的位置 首页 java

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

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

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

更新问题

我用了两个密码

  • 打开JAR文件中的 Pdf 文件
    如果我从
    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” 。我使用了以下代码同一页我的 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 文件,它运行良好。但没有在 PD F和 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);
}  

文章来源:智云一二三科技

文章标题:包中的文件不会从java应用程序中打开

文章地址:https://www.zhihuclub.com/179120.shtml

关于作者: 智云科技

热门文章

网站地图