Java 如何将文本输出到资源文件夹Maven中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21567497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:24:19  来源:igfitidea点击:

How to output text to a file in resource folder Maven

javamavencsv

提问by Jusleong

Here is the structure of my maven project:

这是我的 Maven 项目的结构:

main and test folders are under src folder, java and resources folders are under main folder, in the resources folder, there is a csv file ready for reading.

main 和test 文件夹在src 文件夹下,java 和resources 文件夹在main 文件夹下,在resources 文件夹中,有一个可供读取的csv 文件。

src  
  --main  
    |-- java  
    |-- resources  
           |-- test.csv
test  

Currently, I am trying to overwrite the test.csv file using supercsv library.

目前,我正在尝试使用 supercsv 库覆盖 test.csv 文件。

I know that public CsvMapWriter(Writer writer, CsvPreference preference)method is helpful on that.

我知道这种public CsvMapWriter(Writer writer, CsvPreference preference)方法对此很有帮助。

So, I am trying to use OutputStreamWriter, but how to access that file like using:

所以,我正在尝试使用 OutputStreamWriter,但如何访问该文件,如使用:

 InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("acacia_implexa.csv"));
 mapReader = new CsvMapReader(reader, CsvPreference.STANDARD_PREFERENCE);

回答by Jigar Joshi

You can override the file but that would only work in IDE, if it would be executed as part of jar it would fail because it is not a file any more( its file inside file)

您可以覆盖该文件,但这只适用于 IDE,如果它作为 jar 的一部分执行,它将失败,因为它不再是一个文件(它的文件在文件中)

Better to externalize file and read/overwrite from that location

更好地外部化文件并从该位置读取/覆盖

If you still would like to read this file and overwrite it then you can do something like

如果您仍然想读取此文件并覆盖它,那么您可以执行以下操作

Thread.getclassloader().get resource("/");

This will give you path up to your target/classes directory you can navigate to resources from here using double dots

这将为您提供目标/类目录的路径,您可以使用双点从这里导航到资源

回答by mucaho

You canoutput text to a file in the resourcesfolder, but the process is a bit tedious.

可以将文本输出到文件resources夹中的文件,但过程有点乏味。

  1. Tell Mavento write the location of your resourcesfolder into a file
  2. Read the location of your resourcesfolder in Java
  3. Use that location to write your file to
  1. 告诉 Mavenresources文件夹的位置写入文件
  2. resources在 Java 中读取文件夹的位置
  3. 使用该位置将您的文件写入

Notes

笔记

  • Why bother specifying the location of your resourcesfolder file? Isn't it src/main/resourcesalways? Well no, if you have a nested module structure like

    rootModule   
    ├─ childModule1   
    │  └─ src    
    │     └─ main    
    │        └─ resources    
    └─ childModule2 
       └─ ...  
    

    then the relative path src/main/resourcesresolves to parentModule/src/main/resourceswhich does not exist.

  • Once you write the file to the resourcesfolder, it will not be accessible through Class.getResource(). Class.getResource()provides you with read access to files located in your classpath. The files located in your resourcesfolder are "copied" to your binary output folder (read classpath) during "compilation". In order to access your newly created resource file with the help of Class.getResource(), you will have to recompile & restart the application. However, you can still access it by the location you used for writing the file.
  • 为什么要指定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(),您必须重新编译并重新启动应用程序。但是,您仍然可以通过用于写入文件的位置来访问它。

Guide

指导

  1. add RESOURCE_PATHproperty to the Maven pom, and tell Maven to compile properties found in resource files
  2. add an utility file src/main/resources/RESOURCE_PATH, which only contains the RESOURCE_PATHproperty
  3. extract the RESOURCE_PATHproperty from the utility file in Java
  4. rebuild the project if needed (e.g. if file/folder structure changes)
  1. RESOURCE_PATH属性添加到 Maven pom,并告诉 Maven 编译在资源文件中找到的属性
  2. 添加一个src/main/resources/RESOURCE_PATH仅包含RESOURCE_PATH属性的实用程序文件
  3. RESOURCE_PATH从 Java 实用程序文件中提取属性
  4. 如果需要,重建项目(例如,如果文件/文件夹结构发生变化)

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>

Utility file (src/main/resources/RESOURCE_PATH)

实用程序文件 ( 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());
}

I hope that works. Maybe you need maven resources:resources pluginand do mvn generate-resources process-resources

我希望这有效。也许你需要maven 资源:资源插件并做mvn generate-resources process-resources