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

如何使用config.property文件将任何类型的文件(例如txt文件)写入资源文件夹,但不使用java中的绝对路径文件,java,io,resources,classloader,properties-file,Java,Io,Resources,Classloader,Properties File,如何使用config.property文件将任何类型的文件(例如.txt文件)写入或读取到资源文件夹,但不使用绝对路径文件 我试图解决这个问题,如下所示: ClassLoader classLoader = Setting.class.getClassLoader(); Setting setting = new Setting(); try (InputStream resourceAsStream = classLoader.getResourceAsStream("config.prop

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

我试图解决这个问题,如下所示:

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");

但是,我不希望使用
/src/main/resources
前缀。

如果您的文件位于
资源下,您可以像这样访问它:

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

如果您使用的是Spring,则可以使用:

File File=ResourceUtils.getFile(“类路径:文件名”)

更新:

如果我理解正确,您希望读取位于
src/main/resources
下的文件,而不使用相对路径
/src/main/resources

我创建了一个小演示:

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);
    }
}
输出:

文件存在:true
https://www.gmail.com
项目结构:


资源(类路径上的文件,可能在jar中)可以读取,但不打算写入。您可以使用它们作为模板在文件系统上创建初始副本Joop Eggen

基本上,您想知道资源目录是否有特殊的映射/占位符吗?欢迎使用。您的意思是类似于
System.getProperty(“user.dir”)+“/src/main/resources”
?是的,非常类似于System.getProperty(“user.dir”)+“/src/main/resources”,但不强制使用此字符串“/src/main/resources”@jbааааМааМааааааа1072,但不打算写信给。您可以使用它们作为模板在文件系统上创建初始副本。不,我想使用位于参考资料中的文件,如果没有这一行,我怎么做:“/src/main/resources”p.c但是this->file file file=new file(classLoader.getResource(fileName.getFile());使用proget startgetFile()所在文件夹中的文件生成NullPointerException ooo@Сааааааааааааааааааа107。你需要发布更多关于你的项目结构和代码的信息。
File exists: true
<?xml version="1.0" encoding="utf-8"?>
<config>
    <baseUrl>https://www.gmail.com</baseUrl>
</config>