浅谈getResource和getResourceAsStream

背景:读取mcbuild.jar中的资源文件TestMapper.xml。FileCodeBulder是jar包中的一个类文件。同目录下放着TestMapper.xml文件。
一般来说,读取文件有两种方式:
1.getResource 不可以正常使用
URL url = FileCodeBulder.class.getResource("TestMapper.xml");//这里不能写成"/TestMapper.xml"
上面是获取到类文件同目录下TestMapper.xml,如果文件不存在url会为null。
if (url == null) {
            System.out.println("TestMapper.xml is not exist!");
            return;
}
有趣的是此时url不会null。
String path = url.getPath().replaceAll("%20", " ");
File file = new File(path);//path为 E:/workspace/MIS/IntegManage/WebRoot/WEB-INF/lib/mcbuild.jar!/com/ht/build/TestMapper.xml
System.out.println(file.exists());
//输出为false。这里我想不明白,唯一合理的解估计是 “相对工程,jar包中的文件是不存在的”。

2.getResourceAsStream 可以正常使用
InputStream file = FileCodeBulder.class.getResourceAsStream("TestMapper.xml"); // 这里不能写成"/TestMapper.xml"
        byte[] temp = new byte[1024];
        String content = "";
        int len = 0;
        try {
            while ((len = file.read(temp)) != -1) {
                content += new String(temp, 0, len, "utf-8");
            }
            file.close();
        }
        catch (Exception e) {
            System.out.println(fileName + " is not exist!");
            e.printStackTrace();
        }
        return content;
       
在结尾在闲扯一下FileCodeBulder.class.getResource("TestMapper.xml")和FileCodeBulder.class.getClass().getResource("/TestMapper.xml").
前面的是获得跟FileCodeBulder同目录下的TestMapper.xml文件
而后面的是获得工程class目录下的TestMapper.xml。 如:E:/workspace/MIS/IntegManage/WebRoot/WEB-INF/classes/TestMapper.xml。
两者除了得到的路径不一样,输入的参数也有差异。后面的多了“/”.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值