Java中的资源加载不能正常工作 [英] Resource loading in Java not working as it should

查看:103
本文介绍了Java中的资源加载不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从jar文件加载资源的众所周知的问题。这不是我第一次尝试这样做,但现在它不像我期望的那样工作。

This is the well known problem of loading resources from a jar file. This is not the first time I've tried to do this, but now it doesn't work the way I expect it to.

通常我尝试使用 this.getClass.getResource(foo.png)加载资源,或者 getResourceAsStream()并且它有效。但现在却没有。资源始终为null。

Normally I try to load the Resources with this.getClass.getResource("foo.png"), or getResourceAsStream()and it works. Now however it does not. The Resource is always null.

如果我让 System.out.println(this.getClass.getResource())打印我path(来自eclipse)它显示 / path / to / eclipseproject / package / structure / 。从jar运行它只显示 rsrc:package / structure

If I let System.out.println(this.getClass.getResource("")) print me the path (from eclipse) it shows /path/to/eclipseproject/package/structure/. Running this from a jar it just shows rsrc:package/structure

如果我没记错的话应该打印路径到罐子里。此外,我认为这将打印两种情况下的包结构。我做错了吗?

If I recall correctly this should print the path to the jar. Furthermore I thought this would print the package structure in both cases. Am I doing something wrong?

推荐答案

这就是......

从Jar中提取文件时使用:

When Extracting the file from the Jar use:

this.getClass.getResource("/foo.png")

从可运行的Jar中运行时,引用Jar文件夹路径中的外部文件:

When running from a runnable Jar use, to reference an external file in the Jar folder path:

this.getClass.getResource("foo.png")
// When running this from Eclipse, it would refer to files in project root!

我有一个较低级别的代码,用于确定我在哪里运行以确定正确的路径。

I have a code in the lower level determining where I'm running from to determine the correct path.

这篇关于Java中的资源加载不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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