以jar包为容器的java程序访问一同打到jar包里的配置文件的方法

Java程序有时会被打到jar包里执行,同时src/main/resources里一些配置文件也会被打进去。

比如,src/main/resources下有一个box目录,里面有几个json文件,用maven制作jar包会被一同打进jar里,如果Java程序需要访问,可以采用以下方法:

final String configFolder = "/box";
String configFilePath = configFolder + "/001.json";
logger.info("ConfigFilePath:{}", configFilePath);

InputStream instream = this.getClass().getResourceAsStream(configFilePath);
if (instream == null) {
    String errMsg = String.format("Cannot find configFile at %s", configFilePath);
    throw new Exception(errMsg);
}

BufferedReader bufReader = new BufferedReader(new InputStreamReader(instream));
...

如果路径配置正确,上面红色一行就是核心语句,用它就能访问到json文件,然后使用BufferredReader就能可以了。

--2020-03-25--

posted @ 2020-03-25 08:34  逆火狂飙  阅读(365)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东