java - 写入资源文件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不允许写入资源文件?如果是这样,存储由程序更改的文件(例如日志文件)的最佳位置是哪里
解决方案
然而,目标目录包含一个 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.nio
API 更好:
Path file = Paths.get("src/main/resources/authors/authors.log");
如果是这样,存储由程序更改的文件(例如日志文件)的最佳位置是哪里
除了技术问题,您应该想知道为什么您的应用程序需要修改源代码。它应该只在非常特定的极端情况下完成。
例如,日志文件不必位于源代码中,它们必须位于源代码项目之外,因为它们不构成应用程序源代码的一部分,也不是构建应用程序的工具。
推荐阅读
- git - 如何隐藏远程分支而不从远程删除它们
- vue.js - nginx docker 容器中的 Vue.js 部署破坏了正确的丢失垃圾行为
- javascript - 反应路由器useHistory.push渲染组件但useState,useEffect不更新而不刷新
- json - npm ,纱线,package.json 问题
- amazon-web-services - 我可以使用“AWS Elastic Beanstalk Deploy Application”devops 任务标记 Elastic Beanstalk 应用程序版本吗?
- c# - 在c#编程MJPEGStream url中包含Profile,是什么意思
- primeng - Angular 11 使用带有纯 HTML 表格的 PrimeNG 分页器
- bash - 脚本中的 grep 不起作用,但在 shell 中起作用
- java - 添加变量时 HashSet 的工作原理
- c# - 在文本框中调用带有字符串的方法