【SpringBoot】四种读取 Spring Boot 项目中 jar 包中的 resources 目录下的文件
在 Spring Boot 项目中,你可以使用 ResourceLoader
接口、Resource
抽象类、ClassPathResource
类或 InputStream
来读取位于 resources
目录下的文件。以下是四种方法的示例代码:
- 使用
ResourceLoader
接口:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@Service
public class ResourceService {
@Autowired
private ResourceLoader resourceLoader;
public String readFileFromResources(String fileName) throws IOException {
Resource resource = resourceLoader.getResource("classpath:" + fileName);
InputStream inputStream = resource.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
return reader.lines().reduce((acc, current) -> acc + "\n" + current).orElse("");
}
}
}
- 使用
Resource
抽象类:
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
public class ResourceService {
public String readFileFromResources(String fileName) throws IOException {
Resource resource = new ClassPathResource(fileName);
InputStream inputStream = resource.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
return reader.lines().reduce((acc, current) -> acc + "\n" + current).orElse("");
}
}
}
- 使用
ClassPathResource
类:
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
public class ResourceService {
public String readFileFromResources(String fileName) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(fileName);
InputStream inputStream = classPathResource.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
return reader.lines().reduce((acc, current) -> acc + "\
评论已关闭