【问题标题】:Maven project won't write to file in JARMaven 项目不会写入 JAR 中的文件
【发布时间】:2023-02-24 01:59:36
【问题描述】:

我写了一个方法来写入文件。它在 IDE 中运行程序时有效,但当它是 JAR 文件时无效,因为显然 JAR 是 ZIP。 我如何解决这个问题并写入 JAR 中的文件?

下面的代码有一个将内容写入文件的方法和另一个读取内容的方法。阅读有效,但写作无效。

写入文件的内容将被读取和打印。 test2() 方法只是为了显示 test() 方法是否有效。

import java.io.*;
import java.util.Objects;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Main mainTest = new Main();
        mainTest.test("hello world");
        System.out.println(mainTest.test2());
    }

    private void test(String text) {
        File file = new File(Objects.requireNonNull(getClass().getClassLoader().getResource("test.txt")).getPath());

        try (
                FileWriter fileWriter = new FileWriter(file);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
        ) {
            bufferedWriter.write(text);
        } catch (IOException e) {
            e.getMessage();
        }
    }

    private String test2() {
        try (
                InputStream file = getClass().getClassLoader().getResourceAsStream("test.txt");
                Scanner scanner = new Scanner(file)
        ) {
            String line = "";

            while (scanner.hasNextLine()) {
                line = scanner.nextLine();
            }

            return line;
        } catch (IOException e) {
            e.getMessage();
        }
        return null;
    }
}

【问题讨论】:

  • 文件应该在应用程序外部,并通过首选项、env 或 CLI 变量等进行配置。

标签: java maven


【解决方案1】:

您不能写入 JAR 内的文件。

对不起。

写入其他目录,如临时目录。

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2012-10-11
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多