前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >获取jar包内部的资源文件

获取jar包内部的资源文件

作者头像
用户7798898
发布2020-09-27 16:22:11
1.6K0
发布2020-09-27 16:22:11
举报

通常获取一个资源文件很简单,问题是对于jar包内的资源文件,可能会发生意外。假如这里有一个文件操作的类:

代码语言:javascript
复制
public class FileLoader {
 
    public boolean exists(){
        URL resource = FileLoader.class.getResource("/library/a.txt");
        if(resource==null){
            return false;
        }
        File f = new File(resource.getFile());
        return f.exists();
    }
    public static void main(String[] args) throws IOException {
        FileLoader f = new FileLoader();
        System.out.println(f.exists());
    }
 
}

运行main方法它会读取当前根路径下(src/bin)的资源文件,假如存在目录library和子文件a.txt,这里会打印出true;

现在把这段代码和资源文件打成myfile.jar并运行在一个myeclipse工程中,我们期望也是打印true。然而控制台打印false;将其引入到war工程在tomcat中运行,依然打印false。

也就是说,资源文件的使用类无法找到自己,jar包正常的功能将无法提供。这是一个常见的关于jar路径的问题。

为了试验,在上面的FileLoader类中增加一个方法

代码语言:javascript
复制
public void printPath(){
    System.out.println("/目录:  "+ FileLoader.class.getResource("/").getPath());
    System.out.println("\"\"目录:  "+ FileLoader.class.getResource("").getPath());
    System.out.println("/library目录:  "+ FileLoader.class.getResource("/library").getPath());
        
}

运行后打印结果为:

/目录: /D:/Workspaces/ruleengine/file/target/classes/ ""目录: /D:/Workspaces/ruleengine/file/target/classes/com/file/ /library目录: /D:/Workspaces/ruleengine/file/target/classes/library

重新打包后引入到一个当前myeclipse工程中,一定要以jar包的形式引入,不能通过myeclipse直接关联myfile工程。调用printPath后打印结果为:

/目录: /D:/Workspaces/ruleengine/schoolaround/target/test-classes/ ""目录: file:/D:/Workspaces/ruleengine/schoolaround/lib/myfile.jar!/com/file/ /library目录: file:/D:/Workspaces/ruleengine/schoolaround/lib/myfile.jar!/library

显而易见,获取jar包中的文件路径的格式已经变为*.jar!*(除了第一个),这种格式的路径,不能通过new File的方式找到文件。目前本人也没有找到其它处理方式,欢迎评论指点。在这种情况下,如果想让jar读取到自己的资源文件,可以通过类加载器的getResourceAsStream方法来解决。

修改FileLoader类的exists方法如下:

代码语言:javascript
复制
public boolean exists() throws IOException{
    InputStream resource = FileLoader.class.getResourceAsStream("/library/a.txt");
    if(resource==null){
        return false;
    }
    return true;
}

这时无论是在哪里引入myfile.jar,执行exists方法时都会打印true。也就是说,资源文件一定能够被读取到。

参考文章: https://blog.csdn.net/luo_jia_wen/article/details/50057191

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档