为什么我的 URI 不是分层的? [英] Why is my URI not hierarchical?

查看:30
本文介绍了为什么我的 URI 不是分层的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在资源文件夹中有文件.例如,如果我需要从资源文件夹中获取文件,我喜欢这样:

I have files in resource folder. For example if I need to get file from resource folder, I do like that:

File myFile= new File(MyClass.class.getResource(/myFile.jpg).toURI());             
System.out.println(MyClass.class.getResource(/myFile.jpg).getPath());

我已经测试并且一切有效

路径是

/D:/java/projects/.../classes/X/Y/Z/myFile.jpg

/D:/java/projects/.../classes/X/Y/Z/myFile.jpg

但是,如果我创建 jar 文件,使用 Maven:

But, If I create jar file, using , Maven:

mvn package

...然后启动我的应用程序:

...and then start my app:

java -jar MyJar.jar

我有以下错误:

Exception in thread "Thread-4" java.lang.RuntimeException: ხელმოწერის განხორციელება შეუძლებელია
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
        at java.io.File.<init>(File.java:363)

...文件路径是:

file:/D:/java/projects/.../target/MyJar.jar!/X/Y/Z/myFile.jpg

当我尝试从资源文件夹中获取文件时会发生此异常.在这一行.为什么?为什么在 JAR 文件中有这个问题?你怎么看?

This exception happens when I try to get file from resource folder. At this line. Why? Why have that problem in JAR file? What do you think?

还有其他方法可以获取资源文件夹路径吗?

Is there another way, to get the resource folder path?

推荐答案

你应该使用

getResourceAsStream(...);

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

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

问题是,jar 是一个单独的文件(有点像 zip 文件),其中包含许多文件.从 Os 的 pov 来看,它是一个文件,如果您想访问 文件的一部分(您的图像文件),您必须将其用作流.

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.

文档

这篇关于为什么我的 URI 不是分层的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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