代码实例
getResource
// 获取URL资源路径进行读取
private static void readClassPathByUrl() throws Exception{
URL url = App.class.getClassLoader().getResource("config.properties");
System.out.println(url.getPath());
FileInputStream inputStream = new FileInputStream(url.getPath());
Properties properties = new Properties();
properties.load(inputStream);
Object username = properties.get("username");
System.out.println(username);
inputStream.close();
}
getResourceByStream
// 获取jar包classpath的文件流
private static void readClassPathByStream() throws Exception{
InputStream stream = App.class.getClassLoader().getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(stream);
System.out.println(properties.get("username"));
stream.close();
}
调用方法与待读取文件
代码执行与调试
本地运行
本地运行,两种方式都可以读取到classpath下面的文件
部署jar包运行
总结
- 使用Jar包进行调用getResource方法报错了,并且提示原因为找不到文件,可以仔细看运行时我已经把路径打印出来了,路径是一个绝对路径,并且这个路径明显是错误的,jar包不是一个文件夹,而是一个文件。
- 为啥使用idea本地运行没有报错,因为使用本地运行可以通过路径找到文件,所以没报错
- 读取classpath下的文件是Java开发的常见需求,例如读取excel模板,读取额外的配置文件,在开发过程中推荐使用 getResourceByStream方法,不然打jar包部署调用时就会报错,不管windows系统还是Linux系统都一样