`
xtel
  • 浏览: 21493 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

浅谈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。
两者除了得到的路径不一样,输入的参数也有差异。后面的多了“/”.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics