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

查看:339
本文介绍了为什么我的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天全站免登陆