首页 > 解决方案 > 写入资源文件java?

问题描述

我正在尝试将数据动态写入java中的资源文件,但似乎无法成功。有可能吗?我尝试了几种方法,但都没有奏效。

我有一个主要方法,它代表:

public static void main(String[] args) throws Exception {

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    File file = new File(loader.getResource("authors/authors.log").getFile());

    FileWriter writer = new FileWriter(file);
    System.out.println(file.getAbsolutePath());

    writer.write("Test test \n");

    writer.flush();

    System.out.println(file.getAbsolutePath());

    writer.write("Test 2");

    writer.flush();
    writer.close();

}

执行 main 方法后,没有抛出异常,但 authors.log 文件似乎没有改变,也没有写入数据。

文件是:

src/main/java/main/Main.java

src/main/resource/authors/authors.log

目标/类/作者/authors.log

但是目标目录包含一个authors.log文件,并且所有数据都写入那里。我在某处错了还是只是java不允许写入资源文件?如果是这样,存储由程序更改的文件(例如日志文件)的最佳位置是哪里

标签: javamavenfileresources

解决方案


然而,目标目录包含一个 authors.log 文件,所有数据都写在那里。

这是相当预期的,因为它是您打开和修改的文件。

以下语句使用类加载器来检索文件而不是文件系统:

File file = new File(loader.getResource("authors/authors.log").getFile());

因此,它将检索位于 中的文件,target/classes而不是位于src/main/resources.

通过指定当前工作目录的相对路径来使用文件系统,以便能够更改以下内容 src/main/resources

例如 :

File file = new File("src/main/resources/authors/authors.log");

或使用java.nioAPI 更好:

Path file = Paths.get("src/main/resources/authors/authors.log");

如果是这样,存储由程序更改的文件(例如日志文件)的最佳位置是哪里

除了技术问题,您应该想知道为什么您的应用程序需要修改源代码。它应该只在非常特定的极端情况下完成。
例如,日志文件不必位于源代码中,它们必须位于源代码项目之外,因为它们不构成应用程序源代码的一部分,也不是构建应用程序的工具。


推荐阅读