在 jar 中加载文件

发布于 2024-10-09 19:14:42 字数 281 浏览 0 评论 0原文

我需要将配置文件打包到 jar 中。配置文件位于 jar 文件的根目录下。 但是我收到以下错误:

由以下原因引起:java.lang.IllegalArgumentException:URI 不是分层的 在 java.io.File.(来源不明)

File url = new File(MyClass.class.getClassLoader().getResource("my.conf").toURI());

I need to package a configuration file within a jar. the configuration file is under the root of the jar file.
However I got the following error:

Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.(Unknown Source)

File url = new File(MyClass.class.getClassLoader().getResource("my.conf").toURI());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

单挑你×的.吻 2024-10-16 19:14:42

您应该使用 getResourceAsStream() 代替。如果该文件嵌入在您的 JAR 中,则 URI 很可能是 bundle:// URI

InputStream is = this.getClass().getResourceAsStream("my.conf");

You should use getResourceAsStream() instead. If the file is embedded in your JAR the URI is most likely bundle:// URI

InputStream is = this.getClass().getResourceAsStream("my.conf");
数理化全能战士 2024-10-16 19:14:42

为什么需要文件?如果您需要读取配置,请使用

Class.getResourceAsStream("/my.conf");

这仅需要是包根目录下的一个文件夹中的文件(与 jar 根目录中的相同)

Why do you need a file? IF you need to read the config use

Class.getResourceAsStream("/my.conf");

This will need only to be the file in the one folder with the root of your package( the same as in the root of the jar)

夜雨飘雪 2024-10-16 19:14:42

该文件应与 MyClass 位于同一包中。我刚刚意识到您正在创建一个 File 对象。相反,请尝试使用 getResourceAsStream()。如果您想从类路径资源中读取内容,这是正确的方法。这里是示例

The file should be in the same package as the MyClass. I just realized you are creating a File object. Instead try using getResourceAsStream(). This is the right way if you want to read the contents from a classpath resource. Here is the example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文