java jar 包加载文件问题

  1. 场景:

    A 项目是一个服务,然后部署到本地 maven 仓库里,然后 B 项目依赖 A 项目,调用  A 项目的方法,但是发现,报错,说找不到文件(config.xsv).这就很奇怪了,怎么会呢,自己项目下的

文件怎么找不到呢。

  

  2. 来看下代码

String file =  IpHelper.class.getClassLoader().getResource(ipFile).getFile();
BufferedReader ipRelationReader = FileUtil.readFile(file);

  3. 运行的时候报错  

java.io.FileNotFoundException: file:/Users/zhuzi/software/maven_repo/com/ggstar/ipdatabase/1.0-SNAPSHOT/ipdatabase-1.0-SNAPSHOT.jar!/ipDatabase.csv 
(No such file or directory)

  4.然后就更改如下:

InputStream inputStream = IpHelper.class.getResourceAsStream("/" + ipFile);
BufferedReader ipRelationReader = new BufferedReader(new InputStreamReader(inputStream));

  然后再次运行,就可以找到了,正常运行。搞定。

原文地址:https://www.cnblogs.com/zhuzi91/p/8307464.html