简体   繁体   English

如何使用config.property文件将任何类型的文件(例如txt文件)写入资源文件夹,但不使用Java中的绝对路径文件

[英]How to write any type of file (for example txt file) to a resources folder with the config.property file, but without using absolute path file in java

How to write or read any type of file (for example .txt file) to a resources folder with the config.property file, but without using absolute path file. 如何使用config.property文件将任何类型的文件 (例如.txt文件) 写入或读取到资源文件夹,但不使用绝对路径文件。

I tried to solve this like below: 我试图解决这个问题,如下所示:

ClassLoader classLoader = Setting.class.getClassLoader();
Setting setting = new Setting();

try (InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties")) {
   setting.load(resourceAsStream);
}

String readFileName = setting.getValue("pathSource.txt");
String writeFileName = setting.getValue("outPutPathSourceFile.txt");

String s = System.getProperty("line.separator");

File readFile = new File("./src/main/resources" + File.separator + "pathSource.txt");
File writeFile = new File("./src/main/resources" + File.separator + "outPutPathSourceFile.txt");

However, I don't want using ./src/main/resources prefix. 但是,我不想使用./src/main/resources前缀。

If your file is located under resources you able to access it like: 如果文件位于resources下,则可以像下面这样访问它:

File file = new File(classLoader.getResource(fileName).getFile()); 文件file =新File(classLoader.getResource(fileName).getFile());

if you are using Spring you can use ResourceUtils.getFile() : 如果您使用的是Spring,则可以使用ResourceUtils.getFile()

File file = ResourceUtils.getFile("classpath:fileName") 文件文件= ResourceUtils.getFile(“ classpath:fileName”)

UPDATE: 更新:

If I understand correctly, you want to read file which located under your src/main/resources without relative path usage /src/main/resources . 如果我理解正确,那么您想读取位于src/main/resources下的文件,而没有使用相对路径/src/main/resources

I created small demo: 我创建了一个小演示:

public class ReadResourceFile {
    public static void main(String[] args) throws IOException {
        String fileName = "webAutomationConfig.xml";
        ClassLoader classLoader = ReadResourceFile.class.getClassLoader();
        File file = new File(classLoader.getResource(fileName).getFile());

        System.out.println("File exists: " + file.exists());

        String content = new String(Files.readAllBytes(file.toPath()));
        System.out.println(content);
    }
}

Output: 输出:

File exists: true
<?xml version="1.0" encoding="utf-8"?>
<config>
    <baseUrl>https://www.gmail.com</baseUrl>
</config>

Project structure: 项目结构:

在此处输入图片说明

Resources (files on the class path, possibly inside a jar)can be read, but are not intended to be written to. 可以读取资源(类路径上的文件,可能在jar内),但不能将其写入。 You can use them as template to create an inital copy on the file system. 您可以将它们用作模板在文件系统上创建初始副本。 – Joop Eggen –乔普·艾根(Joop Eggen)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM