访问存储在.jar中的PDF文件

时间:2013-09-26 13:03:56

标签: java file pdf file-io jar

我正在创建一个GUI,我打算添加一个简单的pdf文件作为帮助文件。 我将它包含在资源包中并在此板上搜索,我想出了以下代码:

private void GuideActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File(("Help.pdf"));
        if (!myFile.exists()) {
            // In JAR
            InputStream inputStream = ClassLoader.getSystemClassLoader()
                                .getResourceAsStream("resources/manual.pdf");
            // Copy file
            OutputStream outputStream = new FileOutputStream(myFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
        }
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
        // no application registered for PDFs
    }
}

问题是现在pdf阅读器无法访问该文件,因为它已被java应用程序使用。 有办法解决吗?否则,我只需将文件添加到dist中,然后计算出资源路径。

1 个答案:

答案 0 :(得分:0)

我尝试了您的代码并且效果非常好,请检查您的源代码中是否创建了文件夹resources,其中包含文件manual.pdf。此外,当您创建jar检查这些文件是否已导出时。