如何将pdf文件捆绑在JAR中,以便在从eclipse运行时和打包到jar中时可以平等地访问它?

问题描述 投票:0回答:1

我的项目有多个图像和一个 pdf 文件。项目的 JAR 需要在我们位于多个城市的不同办公室中具有 Linux 或 Windows 的各种 PC 上使用。这就是为什么我希望所有资源都成为同一个 JAR 文件的一部分,以便轻松且无错误地移植。

我已经成功地使用我的图像/图标作为资源访问:

public static final ImageIcon CopyIcon = new ImageIcon(Global.class.getResource("/cct/resources/copy.png"));

但是当我使用类似的代码访问用户手册(pdf)文件时:

File userManual = new File(Global.class.getResource("/cct/resources/manual.pdf").toURI());
Desktop.getDesktop().open(userManual);

...从 eclipse 中运行时,用户手册可以正常打开,但从使用创建的 jar 文件访问时没有响应

Export => Runnable JAR file => 'Extract/Package required libraries into generated JAR'
选项。所有其他选项都可以无缝工作。

我已经尝试了在此处找到的许多解决方案,但没有一个有效,因为其中大多数都适用于其他文件类型,例如txt 或 excel 或图像。

java eclipse pdf jar resources
1个回答
0
投票

感谢@howlger提到的答案,我修改了我的代码如下,使我的pdf可以从eclipse和JAR访问。

public static void openUserManual() {
        File userManual;
        try {
            userManual = new File(Global.class.getResource("/cct/resources/manual.pdf").toURI());
            Desktop.getDesktop().open(userManual); // works when run from eclipse
        }
        catch (Exception ex) {
            try {
                userManual = getResourceAsFile(Global.class.getResource("/cct/resources/manual.pdf").getPath());
                Desktop.getDesktop().open(userManual); // works when run from JAR
            }
            catch (Exception exp) { exp.printStackTrace(); }
        }
    }
    
    private static File getResourceAsFile(String resourcePath) {
        try (InputStream in = Global.class.getResourceAsStream(resourcePath)) {
            if (in == null)
                return null;

            File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
            tempFile.deleteOnExit();

            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                //copy stream
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1)
                    out.write(buffer, 0, bytesRead);
            }
            return tempFile;
        } catch (IOException exp) { exp.printStackTrace(); return null; }
    }
© www.soinside.com 2019 - 2024. All rights reserved.