如何获取.jar资源路径?

new9mtju  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(295)

我正在使用自定义方法从 resources/ 文件夹。在生产过程中编程时,硬编码路径工作得很好( src/main/resources/ ). 但是,在交付时,我需要使此路径相对于.jar根目录。所以我做了这个。

public static Image getImageFromFile(String file)
{
    Image image = null;
    try
    {
        String path = FileUtils.class.getClassLoader().getResource(file).toExternalForm();
        System.out.println(path);

        File pathToFile = new File(path);
        image = ImageIO.read(pathToFile);
    }
    catch (IOException ex) {ex.printStackTrace();}
    return image;
}
file:/C:/Users/Hugo/Desktop/Hugo/Java%20Workspace/ClashBot/bin/main/icons/level-label.png
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at com.lycoon.clashbot.utils.FileUtils.getImageFromFile(FileUtils.java:55)

打印路径有效并指向相应的图片。但是,程序引发了一个ioexception。
为什么找不到文件?

i5desfxk

i5desfxk1#

你跳得太多了。很简单:

FileUtils.class.getResource("path.png");
// -OR-

try (var in = FileUtils.class.getResourceAsStream("path.png")) {
    // in is an inputstream.
}

这就是你所需要的。注意,这意味着 path.png 文件的搜索位置与fileutils所在的位置完全相同(甚至是相同的“subdir”)。所以如果你有,比如说,关于 C:\Projects\Hugo\MyApp\myapp.jar 如果你解开它,你会发现里面 com/foo/pkg/FileUtils.class ,然后是字符串 path.png 在那个jar里看看 com/foo/pkg/path.png . 换句话说, AnyClass.class.getResource("AnyClass.class") 将让类找到自己的类文件。如果你想从jar的“根”开始,添加一个斜杠,即。 FileUtils.class.getResource("/path.png") 在同一个jar里看 /path.png 在那个jar里。 getResource 返回url。 getResourceAsStream 返回一个流(需要关闭;像我一样使用try with resources)。几乎所有使用api的资源都会将这两个资源中的一个作为输入。例如,imageio这样做;它甚至需要一个url,这样您就可以使用其中一个:

var image = ImageIO.read(FileUtils.class.getResource("imgName + ".png"));

对。这是单行线。这将直接从jar文件中加载图像!

iszxjhcz

iszxjhcz2#

你可以试着用一个稍微不同的电话,像这样:

java.net.URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(file);
String filePath = URLDecoder.decode(fileUrl.getPath(), "UTF-8");
image = ImageIO.read(filePath);

相关问题