java 加载资源时“URI不是分层的”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25465542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:04:47  来源:igfitidea点击:

"URI is not hierarchical" when loading resource

javaresourcesuriclassloaderillegalargumentexception

提问by user2733845

I need the URI of a file (which I put in the resources directory). If I use

我需要一个文件的 URI(我把它放在资源目录中)。如果我使用

MyClass.class.getClassLoader().getResource(resource)

I get

我得到

java.lang.IllegalArgumentException: URI is not hierarchical

Otherwise, if I use ClassLoader.getSystemResource(resource)it returns null.

否则,如果我使用ClassLoader.getSystemResource(resource)它返回null.

回答by Peter Kennedy

Are you loading the file from inside a jar? If so, the OS is unable to form a java Fileinstance from inside a jar. To be able to load it, try open it as a Stream. "filepath" should start with a "/".

您是从 jar 中加载文件吗?如果是这样,操作系统将无法File从 jar 内部形成 java实例。为了能够加载它,请尝试将其作为流打开。" filepath" 应该以 " /"开头。

MyClass.class.getClass().getResourceAsStream( filepath );

回答by Raj Hirani

You should be using

你应该使用

getResourceAsStream(...);

getResourceAsStream(...);

when the resource is bundled as a jar/war or any other single file package for that matter.

当资源被捆绑为 jar/war 或任何其他与此相关的单个文件包时。

See the thing is, a jar is a single file (kind of like a zip file) holding lots of files together. From Os's pov, its a single file and if you want to access a part of the file(your image file) you must use it as a stream.

看到的事情是,jar 是一个单独的文件(有点像 zip 文件),将许多文件放在一起。从 Os 的 pov 来看,它是一个文件,如果您想访问文件的一部分(您的图像文件),您必须将其用作流。