springboot打成jar包后读取配置resources下的文件(已解决)

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方法处理流就行了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容