getResource()无法读取jar内部目录的内容 [英] getResource() unable to read contents of a directory inside jar

查看:506
本文介绍了getResource()无法读取jar内部目录的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚解决了这个问题,jar中的主类无法读取文件夹的内容。
该类包含

I just came around this issue that the main class inside jar is unable to read the contents of a folder. The class contains

String path = "flowers/FL8-4_zpsd8919dcc.jpg";
    try {
        File file = new File(TestResources.class.getClassLoader()
                                .getResource(path).getPath());
        System.out.println(file.exists());
    } catch (Exception e) {
        e.printStackTrace();
    }

这里sysout返回 false

Here sysout returns false.

但是,当我尝试这样的事情时,它会起作用

But when I try something like this it works

    String path = "flowers/FL8-4_zpsd8919dcc.jpg";
    FileOutputStream out = null;
    InputStream is = null;
    try {
        is = TestResources.class.getClassLoader().getResourceAsStream(path);
        byte bytes[] = new byte[is.available()];
        is.read(bytes);
        out = new FileOutputStream("abc.jpg");
        out.write(bytes);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

getResourceAsStream()能够读取jar中文件夹的路径,但是 getResource()无法读取它,

getResourceAsStream() is able to read the path of the folder inside jar but getResource() is unable to read it,

为什么是这样的,这两种方法对jar内容的读取机制有什么区别。
简单jar的内容

why is it so and what is the difference between the reading mechanism of these two methods for contents inside jar. The contents of the simple jar

推荐答案

两者 getResource() getResourceAsStream()能够在jar中找到资源,他们使用相同的机制来定位资源。

Both getResource() and getResourceAsStream() are able to find resources in jar, they use the same mechanism to locate resources.

但是当你构造时来自 URL 文件,表示jar中的条目, File.exists() 将返回 false 文件不能用于检查jar / zip中的文件是否存在。

But when you construct a File from an URL which denotes an entry inside a jar, File.exists() will return false. File cannot be used to check if files inside a jar/zip exists.

您只能使用 File.exists ,它们位于本地文件系统上(或附加到本地文件系统)。

You can only use File.exists which are on the local file system (or attached to the local file system).

这篇关于getResource()无法读取jar内部目录的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆