springboot怎么读取相对路径文件

avatar
作者
筋斗云
阅读量:0

在Spring Boot中,可以使用ResourceLoader来读取相对路径文件。可以将文件放置在项目的resources目录中,然后使用ResourceLoader读取该文件。

以下是一个示例:

import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @Component public class FileHelper { private final ResourceLoader resourceLoader; public FileHelper(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public String readFile(String filePath) throws IOException { Resource resource = resourceLoader.getResource(filePath); BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream())); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); } reader.close(); return content.toString(); } } 

在上述示例中,FileHelper通过构造函数注入了ResourceLoader,然后使用resourceLoader.getResource(filePath)获取相对路径文件的Resource对象。接下来,使用Resource对象的getInputStream()方法获取文件的输入流,并使用BufferedReader逐行读取文件内容。最后,将文件内容转换为字符串并返回。

你可以在任何Spring组件中使用FileHelper来读取相对路径文件:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.CommandLineRunner; import java.io.IOException; @SpringBootApplication public class MyApplication implements CommandLineRunner { private final FileHelper fileHelper; @Autowired public MyApplication(FileHelper fileHelper) { this.fileHelper = fileHelper; } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Override public void run(String... args) throws IOException { String content = fileHelper.readFile("classpath:example.txt"); System.out.println(content); } } 

在上述示例中,MyApplication使用@Autowired注解将FileHelper注入到MyApplication中。在run方法中,调用fileHelper.readFile("classpath:example.txt")来读取resources目录下的example.txt文件,并输出文件内容。

需要注意的是,classpath:前缀是用于指定相对路径文件的前缀,确保正确地从resources目录中读取文件。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!