在 jar 中加载文件
我需要将配置文件打包到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用
getResourceAsStream()
代替。如果该文件嵌入在您的 JAR 中,则 URI 很可能是 bundle:// URIYou should use
getResourceAsStream()
instead. If the file is embedded in your JAR the URI is most likely bundle:// URI为什么需要文件?如果您需要读取配置,请使用
这仅需要是包根目录下的一个文件夹中的文件(与 jar 根目录中的相同)
Why do you need a file? IF you need to read the config use
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)
该文件应与 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.