【问题标题】:File is not opening in java which is inside jar file文件未在 jar 文件内的 java 中打开
【发布时间】:2013-09-25 16:10:51
【问题描述】:

我试图从我的 java 应用程序中打开文件。使用来自

的以下代码

Open PDF file on fly from Java application

代码:

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File("/path/to/file.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
    // no application registered for PDFs
    }
}

当我使用如下路径时:

"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf" 

它打开了。但是我的文件在我的包里

files/test.pdf 

我用过

files\\test.pdf 

它显示以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.

为什么?任何想法...我想将我的文件包含在我的 jar 文件中,该文件可以在用户需要时从我的应用程序中打开。

谢谢...

【问题讨论】:

  • 如果该类的文件在 src 中,则将路径更改为 files/test.pdf
  • 为什么要用files\\test.pdf打开files/test.pdf
  • @Tichodroma 实际上C:\\Users\\kalathoki\\Documents... 工作所以我尝试了files\\test.pdftest.pdf 文件在files 包内
  • 您尝试新的path/to 而不是/path/to 吗? new 也可以尝试显示new File(".");的绝对路径,肯定有帮助
  • 我没有阅读I want to keep my file inside my project jar file. 部分,抱歉。使用InputStream is = System.class.getResourceAsStream("/path/to/file.pdf"); 获取InputStream

标签: java file-io fileinputstream fileoutputstream


【解决方案1】:

getDesktop#open 只允许从文件系统打开文件。一种解决方案是将 PDF 文件保存在本地文件系统上并从那里读取。这样就无需从 JAR 本身中提取文件,因此效率更高。

【讨论】:

  • 其实不是这样,Linux 下 getDesktop().open() 允许打开 jar 中的文件,Windows 显然不允许。在您链接的文档中,他们没有提到您描述的限制。
【解决方案2】:

很遗憾,您无法通过桌面加载包含在 jar 中的文件。

但是,您并非没有选择。一个很好的解决方法是创建一个临时文件,然后按照详细说明打开它here

祝你好运!

【讨论】:

    【解决方案3】:

    假设 test.pdf 在包文件中,试试这个:

    File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
    

    【讨论】:

      【解决方案4】:

      此代码运行正常,请使用此代码在 jar 文件中打开 pdf 文件

          try {
              // TODO add your handling code here:
              String path = jTextField1.getText();
              System.out.println(path);
              Path tempOutput = null;
              String tempFile = "myFile";
              tempOutput = Files.createTempFile(tempFile, ".pdf");
              tempOutput.toFile().deleteOnExit();
              InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
              Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
              if(Desktop.isDesktopSupported())
              {
                  Desktop dTop = Desktop.getDesktop();
                  if(dTop.isSupported(Desktop.Action.OPEN))
                  {
                      dTop.open(tempOutput.toFile());
                  }
              }
          } catch (IOException ex) {}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-28
        • 2013-08-09
        • 2011-11-04
        • 2017-12-16
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 2011-06-05
        相关资源
        最近更新 更多