当时的一个项目 需要读取resources下的文件夹和里面的文件,windows没啥问题,但是linux就是不行
当时用的是
String path=LastdataBusiness.class.getClassLoader().getResource(file).getPath();String str= readJsonFile.myReadJsonFile(path);
file是文件路径比如“momitor\target”
在ide中运行没问题,jar就不行了
因为打包之后他会以绝对路径去找文件
无法找到jar中的文件,而jar也算是一种压缩文件 一这种形式根本找不到
像这种错误(linux环境)
file:/root/hawk-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/json/host/get.json(没有那个文件或目录)
有两种方法
第一种
这是我的结构
参考大佬的写法搞定
InputStream is=this.getClass().getResourceAsStream("/json/host/config.json");BufferedReader br=newBufferedReader(newInputStreamReader(is));String s="";String configContentStr="";try{while((s=br.readLine())!=null){
configContentStr= configContentStr+s;}}catch(IOException e){
e.printStackTrace();}
参考地址
https://www.jianshu.com/p/97cdf3986fa4
https://juejin.cn/post/6844903705255346184#heading-4
第二种
这个不是很建议,虽然也可以解决问题
不把资源包打进jar,放在linux中的一个文件夹 然后ide中设置路径
可以参考这个https://www.shuzhiduo.com/A/VGzlgGMwdb/