Java程序有时会被打到jar包里执行,同时src/main/resources里一些配置文件也会被打进去。json
好比,src/main/resources下有一个box目录,里面有几个json文件,用maven制做jar包会被一同打进jar里,若是Java程序须要访问,能够采用如下方法:maven
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就能能够了。this
--2020-03-25--spa