java - 写入资源文件java?

标签 java maven file resources

我正在尝试将数据动态写入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

target/classes/authors/authors.log

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

最佳答案

However the target directory contains an authors.log file and all the data is written there.

这是预料之中的,因为它是您打开和修改的文件。

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

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.nio API:

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

If so where is the best place to store files which are changed by the program (e.g. log files)

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

关于java - 写入资源文件java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446731/

相关文章:

java.lang.ClassNotFoundException : org. jboss.logging.Logger 错误

java - 如何将 Jess(.jar 文件)库转换为 .dex 文件,或在 Android 上运行 java 类文件?

java - 部署应用程序时未找到 DefaultSpringSecurityContextSource

Python UTF-16 编码十六进制表示

java - 从jar中读取资源文件

java - Java 中的 listFiles() 方法在 .jar 中不起作用

java - 尝试将 vlcj 媒体播放器嵌入 JPanel 内的 WindowsCanvas

java - 如何使 JAXB 注释并提供 equals/hashcode 实现

java - Maven 程序集 : NoClassDefFoundError

maven - SSD 驱动器会使 maven 构建得更快吗?