jar包中如何读取项目中Resource下的文件

今天遇到一个巨大的坑就是一个简单的读取项目中的一个config.json文件。在本地是正常的,但是打包成jar包在linux上运行的时候死活找不到。
下面是我的项目结构


JIGOU.png

就是为了读取配置文件config.json的内容
刚开始是通过文件路径然后通过readFile("文件路径")的方式读取,但是使用过

 this.getClass().getResource("/").getPath()+"config.json"  //本地是可以的,但是打包成jar包之后再服务器中打印出的路径是一串数字。
String configPath = ResourceUtils.getFile("classpath:config.json").getAbsolutePath(); //也是不行

后面再网上找了使用getResourceAsStream() 方法搞定,代码如下

  InputStream is = this.getClass().getResourceAsStream("/config.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s="";
        String configContentStr = "";
        try {
            while((s=br.readLine())!=null) {
                configContentStr = configContentStr+s;
            }
        } catch (IOException e) {

                    e.printStackTrace();
        }

顺便记录一下java中获取路径的一些方法

//获取类路径
 String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
 String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
//因为程序已经被打包成jar包,所以getPath()和getFile()在这里的返回值是一样的。都是/xxx/xxx.jar这种形式。如果路径包含Unicode字符,还需要将路径转码
path = java.net.URLDecoder.decode(path, "UTF-8");

//利用了java运行时的系统属性来得到jar文件位置,也是/xxx/xxx.jar这种形式。
String path = System.getProperty("java.class.path");

你可能感兴趣的:(jar包中如何读取项目中Resource下的文件)