以jar包爲容器的java程序訪問一同打到jar包裏的配置文件的方法

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