获取资源库中文件的路径,即使它在 jar 中

时间:2021-01-26 12:14:22

标签: java

我在资源中有一个 Json 文件,我正在使用此代码来使用它所拥有的信息:

JsonClass myWantedInfo;
Gson gson = new GsonBuilder().serializeNulls().create();
URL res = getClass().getClassLoader().getResource("file.json");
Writer writer = Files.newBufferedWriter(Paths.get(res.toURI()));
gson.toJson(myWantedInfo, writer);
writer.close();

当我使用我的 IDE(Eclipse - Spring Tool Suite 4)时,此代码有效。但是当我构建我的项目的 JAR 时,它会抛出一个错误(FileNotFoundException)。 我搜索了一下,发现原因是在我的代码中,源代码在 src/main/resources 中,但在 jar 中位于根目录中。但是我不知道如何解决这个问题。

为了构建 jar,我转到我的 pom 所在的路径,并使用 cmd,我使用:mvn clean install。

抱歉我的英语不好。

2 个答案:

答案 0 :(得分:0)

资源旨在用于系统的输入 - 而在这里您试图写入一个。尝试写入运行时 jar 似乎非常容易出错(更不用说糟糕的形式)。因此,您的 FileNotFoundException 实际上符合预期(没有名为 file.json 的资源)。您应该从 OutputStreamWriter 创建您的输出对象(FilePath)(即,使用当前的工作目录或使用 java.io 方法在运行时的 java.io.tmpdir 目录中创建临时文件)。

要么是你的代码“转错了方向”,导致你读写混乱。

答案 1 :(得分:0)

我在读取属性文件时遇到了类似的错误。经过一番研究,我将这段代码添加到 pom:

<build>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>

这就是我从文件中读取的方式:

/**
 * loads default config from internal source
 *
 * @return true/false upon success/failure of loading config
 */
private static boolean loadDefault() {

    if (null != properties) return false;

    try (InputStream resourceStream = Config.class.getClassLoader().getResourceAsStream("config.properties")) {
        properties = new Properties();
        properties.load(resourceStream);
        return true;

    } catch (NullPointerException | IOException exception) {

        String detail = ExceptionHandler.format(exception, "Could not load default config");
        log.error(detail);

        properties = null;
        return false;
    }
}
相关问题