单击按钮打开文件

时间:2014-11-12 23:05:52

标签: java file

我有一个java项目,其中一个按钮打开一个pdf文件 当项目导出到runnable jar时,文件无法打开!!

这是我的按钮监听器

public void about (Event event){

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


}

1 个答案:

答案 0 :(得分:0)

永远不要引用src目录中的内容,在构建项目时,src目录将不存在。

您的应用程序上下文中包含的内容(特别是那些包含在Jar文件中的内容)通常无法作为File访问(就像您从文件系统中访问的那样),它们将成为您应用程序中的条目Jar文件。

在这种情况下,您需要在打开文件之前解压缩文件。

您可以做的是,使用Class#getResourceAsStream并将生成的InputStream复制到磁盘

例如......

try (InputStream is = getClass().getResourceAsStream("/application/Documenation.pdf")) {
    File file = File.createTempFile("Documentation", ".pdf");
    file.deleteOnExit();
    try (OutputStream os = new FileOutputStream(file)) {
        byte[] buffer = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
    }
    Desktop.getDesktop().open(file);
} catch (IOException exp) {
    exp.printStackTrace();
}