Java-EE 中的 class.getResource() (wildfly) [英] class.getResource() within Java-EE (wildfly)

查看:42
本文介绍了Java-EE 中的 class.getResource() (wildfly)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java-EE (Wildfly v.17)

I am using Java-EE (Wildfly v.17)

我想访问位于 WEB-INF/classes/config.txt 中的文件config.txt".

I want to access the file "config.txt" which resides within WEB-INF/classes/config.txt.

我知道一种使用 servletContext 的解决方案.

I know one solution with servletContext.

但是,我想知道为什么一些常见的东西不起作用:

// prints: file:/Users/test/server/wildfly-17.0.1.Final/modules/system/layers/base/org/jboss/as/ejb3/main/timers/
// why does this point to "ejb3/main/timers" ???
log.info(User.class.getResource("/").toExternalForm());

这些都不起作用,我总是得到 java.lang.NullPointerException(没有找到文件,但文件在那里!)

Nothing of those works, I always get java.lang.NullPointerException (no file found, but the file is there!)

var resource = User.class.getResource("/config.txt");


var resource = User.class.getResource("/WEB-INF/classes/config.txt")


var resource = User.class.getResource("config.txt")


var resource = getClass().getResource("config.txt")


var resource = Thread.currentThread().getContextClassLoader().getResource("config.txt")

如何在 Wildfly 中使用 getResource()getResourceAsStream() ?

How can I use getResource() or getResourceAsStream() within Wildfly?

(或者我应该把 config.txt 放在哪里才能使用 getResource() ?)

(Or where should I put the config.txt to be able to use getResource() ?)

推荐答案

访问 WEB-INF/classes/config.txt 文件中数据的最简单方法是使用 java.lang.Class.getResourceAsStream("/config.txt"),您的第一个示例涵盖了这一点.

The easiest way to get access to the data in your WEB-INF/classes/config.txt file is to use java.lang.Class.getResourceAsStream("/config.txt"), which is covered by your first example.

如果返回 null 则文件不存在.如果您使用 Maven 构建,那么最常见的原因是将 config.txt 放在 src/main/java 目录中而不是 src/main/资源.

If this returns null then the file is not present. If you're building with Maven then the most common reason for this is placing config.txt in the src/main/java directory instead of src/main/resources.

尝试使用 java.lang.Class.getResource("/config.txt") 将以失望结束,因为返回的 URL 可能包含一个难以使用或无法使用的方案,例如jar://..."或vfs://...".您不能依赖 WildFly 为类加载器资源返回file://.."样式的 URL.

Attempts to use java.lang.Class.getResource("/config.txt") will end in disappointment because the URL that is returned will likely contain a scheme that is tricky or impossible to use, such as "jar://..." or "vfs://...". You cannot rely upon WildFly to return a "file://.." style of URL for a class-loader resource.

这篇关于Java-EE 中的 class.getResource() (wildfly)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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