spring boot 项目读取自定义配置文件的坑
springboot读取配置文件
一般情况下我们通过ResourceUtils.getFile(“classpath:config.json”)就可以读取自定义的配置文件
如果是打war包后也可以读取,但是如果你打的是jar包就不可以,jar包找不到classpath的路径
1.以下是亲测成功示例打成jar包放到linux服务器跑
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.json");
String configContent = this.readFile( inputStream );
System.out.println(configContent);
readFile是自定义的一个函数,用来处输入流返回一个字符串
/*
* 读取配置文件
*/
private String readFile ( InputStream inputStream ) throws IOException {
StringBuilder builder = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(inputStream , "UTF-8" );
BufferedReader bfReader = new BufferedReader( reader );
String tmpContent = null;
while ( ( tmpContent = bfReader.readLine() ) != null ) {
builder.append( tmpContent );
}
bfReader.close();
} catch ( UnsupportedEncodingException e ) {
// 忽略
}
return this.filter( builder.toString() );
}
// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
private String filter ( String input ) {
return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" );
}
2.这个是原来的写法,打成jar包放到linux服务器后找不到配置文件,会报错
String configPath = ResourceUtils.getFile("classpath:config.json").getAbsolutePath();
String configContent = this.readFile( configPath );
之前的readFile是这样的
/*
* 读取配置文件
*/
private String readFile ( String path ) throws IOException {
StringBuilder builder = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(path) , "UTF-8" );
BufferedReader bfReader = new BufferedReader( reader );
String tmpContent = null;
while ( ( tmpContent = bfReader.readLine() ) != null ) {
builder.append( tmpContent );
}
bfReader.close();
} catch ( UnsupportedEncodingException e ) {
// 忽略
}
return this.filter( builder.toString() );
}
3.其他两种方式
InputStream inputStream = new ClassPathResource("config.json").getInputStream();
..................
// 如上成功示例,调用readFile方法处理流就行了
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.json");
..................
// 如上成功示例,调用readFile方法处理流就行了