这是我的maven项目的结构:
main和test文件夹在src文件夹下,java和resources文件夹在main文件夹下, 在资源文件夹中,有一个可供读取的 csv 文件。
src
--main
|-- java
|-- resources
|-- test.csv
test
目前,我正在尝试使用 supercsv 库覆盖 test.csv 文件。
我知道 public CsvMapWriter(Writer writer, CsvPreference preference)
方法对此很有帮助。
所以,我正在尝试使用 OutputStreamWriter,但是如何访问该文件,例如使用:
InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("acacia_implexa.csv"));
mapReader = new CsvMapReader(reader, CsvPreference.STANDARD_PREFERENCE);
最佳答案
您可以将文本输出到resources
文件夹中的文件,但是这个过程有点乏味。
- Tell Maven将您的
resources
文件夹的位置写入文件 - 在 Java 中读取您的
resources
文件夹的位置 - 使用该位置将您的文件写入
注意事项
为什么要指定您的
这样的嵌套模块结构resources
文件夹文件的位置?src/main/resources
不是一直都是吗?好吧,如果你有一个像rootModule ├─ childModule1 │ └─ src │ └─ main │ └─ resources └─ childModule2 └─ ...
然后相对路径
src/main/resources
解析为不存在的parentModule/src/main/resources
。- 将文件写入
resources
文件夹后,将无法通过Class.getResource()
访问它。Class.getResource()
为您提供对类路径中文件的读取权限。resources
文件夹中的文件在“编译”期间“复制”到二进制输出文件夹(读取类路径)。为了在Class.getResource()
的帮助下访问您新创建的资源文件,您必须重新编译并重新启动应用程序。但是,您仍然可以通过用于写入文件的位置访问它。
指南
- 将
RESOURCE_PATH
属性添加到 Maven pom,并告诉 Maven 编译在资源文件中找到的属性 - 添加一个实用程序文件
src/main/resources/RESOURCE_PATH
,它只包含RESOURCE_PATH
属性 - 从 Java 实用程序文件中提取
RESOURCE_PATH
属性 - 如果需要重建项目(例如,如果文件/文件夹结构发生变化)
POM
<project>
...
<properties>
<RESOURCE_PATH>${project.basedir}/src/main/resources</RESOURCE_PATH>
</properties>
...
<build>
...
<resources>
<resource>
<directory>${RESOURCE_PATH}</directory>
<filtering>true</filtering>
</resource>
</resources>
....
</build>
...
</project>
实用程序文件(src/main/resources/RESOURCE_PATH
)
${RESOURCE_PATH}
Java
/**
* Reads the relative path to the resource directory from the <code>RESOURCE_PATH</code> file located in
* <code>src/main/resources</code>
* @return the relative path to the <code>resources</code> in the file system, or
* <code>null</code> if there was an error
*/
private static String getResourcePath() {
try {
URI resourcePathFile = System.class.getResource("/RESOURCE_PATH").toURI();
String resourcePath = Files.readAllLines(Paths.get(resourcePathFile)).get(0);
URI rootURI = new File("").toURI();
URI resourceURI = new File(resourcePath).toURI();
URI relativeResourceURI = rootURI.relativize(resourceURI);
return relativeResourceURI.getPath();
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) throws URISyntaxException, IOException {
File file = new File(getResourcePath() + "/abc.txt");
// write something to file here
System.out.println(file.lastModified());
}
希望有用。也许你需要 maven resources:resources plugin并执行 mvn generate-resources process-resources
关于java - 如何将文本输出到资源文件夹 Maven 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567497/