在SpringBoot应用中,经常需要读取打包在jar包中的资源文件,比如配置文件、模板文件等。这些资源文件通常放在src/main/resources目录下,在打包成jar包后,它们会被存储在jar包的根目录下。本文将介绍4种在SpringBoot中读取这些资源文件的方法。
部署后,项目是通过打成 jar 包运行的,里面的文件是没有实际路径的(只有相对于项目名的相对路径)。
这是一个公共方法,用来读取文件中的内容的方法,通过T.class.getClassLoader().getResourceAsStream() 方法。
比如要读取 config 文件夹下的 test.properties 文件:
public static void printFileContent(Object obj) throws IOException {
if (null == obj) {
throw new RuntimeException("参数为空");
}
BufferedReader reader = null;
// 如果是文件路径
if (obj instanceof String) {
reader = new BufferedReader(new FileReader(new File((String) obj)));
// 如果是文件输入流
} else if (obj instanceof InputStream) {
reader = new BufferedReader(new InputStreamReader((InputStream) obj));
}
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
此方法是从 classpath 路径(即:src 或 resources 路径下)下查找文件的,所以,路径前不需要加 “/”。
读取方法:
public class ResourceUtil {
public void getResource(String fileName) throws IOException{
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
printFileContent(in);
}
public static void main(String[] args) throws IOException {
new ResourceUtil().getResource("config/test.properties");
}
}
public void getResource2(String fileName) throws IOException{
InputStream in = this.getClass().getResourceAsStream("/" + fileName);
printFileContent(in);
}
public static void main(String[] args) throws IOException {
new ResourceUtil().getResource2("config/test.properties");
}
本方法是从 classpath 路径(即:src 或 resources 路径下)下查找文件的,但它的路径前需要加 “/” ,这个是跟读取的文件与当前.class 文件的位置有关。
可以看看编译后的文件路径:
当前文件 ResourceUtil.class 与要加载的文件 test.properties 的位置如上: test.properties 和 ResourceUtil.class 不在同一个文件夹下,所以读取的时候是要带上相对路径的,那么,这会有两种情况:
public void getResource3(String fileName) throws IOException{
ClassPathResource classPathResource = new ClassPathResource(fileName);
printFileContent(classPathResource.getInputStream());
}
public static void main(String[] args) throws IOException {
new ResourceUtil().getResource3("config/test.properties");
}
SpringBoot提供了@Value注解,它可以用来注入配置文件中的值,包括从jar包中的资源文件中读取。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConfigPropertiesReader {
@Value("${app.config.value}")
private String configValue;
public void printConfigValue() {
System.out.println("Config Value: " + configValue);
}
}
在application.properties或application.yml文件中,可以这样指定资源文件的位置:
app.config.value=classpath:config.properties