【问题标题】:How to copy folder's out of resources from jar both in runtime and dev-env?如何在运行时和 dev-env 中从 jar 中复制文件夹的资源?
【发布时间】:2019-05-17 14:25:22
【问题描述】:

我目前正在制作一款具有预先制作的关卡的游戏,并且我目前将它们存储在资源中。我想要一个解决方案来解决如何在生产和开发环境中从 jar 中提取文件夹。

我尝试使用下面给定的方法复制文件夹并将 src 传递为File defaultWorld = new File(GameData.class.getClassLoader().getResource("worlds/").getFile()); 和目的地为private static File worldsDir = new File("run/worlds");

public static void copyFolder(File src, File dest) {
    try {
        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String[] files = src.list();

            for (String file : files) {
                copyFolder(new File(src, file), new File(dest, file));
            }
        } else {
            try (InputStream in = new FileInputStream(src)) {
                try (OutputStream out = new FileOutputStream(dest)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    //copy the file content in bytes
                    while ((length = in.read(buffer)) > 0) {
                        out.write(buffer, 0, length);
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我希望上述方法适用于开发环境和生产环境,但在打开文件输出流时会抛出 FileNotFoundException

【问题讨论】:

    标签: java file-io java-8 game-development


    【解决方案1】:

    不能列出 jar 中的资源。

    您想到的任何解决方法都是不可靠的。

    • 从不调用 URL 的getFile() 方法。它返回一个有效的文件名;它只返回 URL 的路径和查询部分,任何百分比转义都完好无损。此外,jar 条目不是file: URL,因此资源路径在引用 jar 条目时永远不能是有效的文件名。
    • 在 jar 文件中列出内容的唯一方法是遍历所有 jar 条目,但甚至不能保证您可以访问您的 jar,因为不能保证 ClassLoaders 是 URLClassLoaders,而且通常不能保证使用jar: URL。
    • 你甚至不能依赖 MyApplication.class.getProtectionDomain().getCodeSource(),因为getCodeSource() can return null.

    如果您想从 jar 中复制多个文件,以下是一些可靠的方法:

    • 硬编码计划复制的资源列表。这是您的应用程序,因此您知道要放入 jar 中的文件。
    • 在 jar 中保留一个文本文件,其中包含要复制的资源路径列表。
    • 将您的资源存储在嵌入到您的 jar 中的单个 zip 存档中,并使用包装 MyApplication.class.getResourceAsStream 的 ZipInputStream 自行提取。

    【讨论】:

    • 谢谢第二种方法/答案是我想我要做的事情。感谢您的详细解释。
    猜你喜欢
    • 2016-07-14
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2012-06-16
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多