0

我试图从我的 java 应用程序中打开文件。使用以下代码

从 Java 应用程序即时打开 PDF 文件

代码:

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 文件中,该文件可以在用户需要时从我的应用程序中打开。

谢谢...

4

4 回答 4

1

getDesktop#open只允许从文件系统打开文件。一种解决方案是将 PDF 文件保存在本地文件系统上并从那里读取。这消除了从 JAR 本身提取文件,因此更有效。

于 2013-09-25T16:20:16.360 回答
1

不幸的是,您无法通过 jar 中包含的 Desktop 加载文件。

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

祝你好运!

于 2013-09-25T16:24:58.443 回答
1

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

File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
于 2013-09-25T16:27:08.153 回答
0

此代码工作正常请使用此代码在 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) {}
于 2016-02-23T01:43:05.397 回答