本文介绍了JAVA getResourceAsStream()文件的真实路径字符串解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NetBeans 8.0.2(我知道已经有v8.2了,但对我来说它有很多错误,所以我又回到了v8.0.2),我需要一个指向.obj文件的字符串路径作为参数属性如下:

I am using NetBeans 8.0.2 (I know there already is v8.2 but it has a lot of bugs for me so I got back to v8.0.2) and I need a string path to my .obj file for a parameter attribute like this:

api.parameter("filename", "obj/someFile.obj");

上面的示例在我的应用程序的早期版本中起作用,在该应用程序中,我将.obj文件放置在与.jar文件位于同一目录中的名为"obj"的文件夹中,但是现在,我试图将其包含在JAR本身的代码:

Above example worked in a previous version of my app where I had that .obj file placed in a folder called "obj" in the same directory as my .jar file, but now as I am trying to rather include it in the JAR itself with code:

api.parameter("filename", MyClass.class.getResourceAsStream("/someFile.obj").toString());

...它不再起作用,因为路径字符串解释不是文件的路径,看起来更像这样:

...it is not working anymore as the path string interpretation is not a path to a file, it looks more like this:

java.io.BufferedInputStream@215d7ea7

...,当然,我的代码期望的是类似正常路径字符串的东西,我会以这种伪代码的方式说些什么:

...where, of course, my code is expecting something like normal path string, I would said something in this pseudo-code manner:

api.parameter("filename", "<this.jar>/someFile.obj");

因此,在对StackOverflow进行了一些摆弄之后,我发现了一些代码,我认为这些代码实际上可以使我直接将该路径放置为字符串:

So after a fiddling a bit around StackOverflow I've found pieces of code that I thought could actually enable me to directly place that path as a string:

URL jar = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
api.parameter("filename", jar + "/someFile.obj");

但是令人惊讶的是,尽管我检查了好几次文件是否确实存在于我的内置jar文件中(是​​的,它存在于根目录中),它仍然给我这个错误:

But surprisingly although I checked several times if the file actually really exist in my built jar file (and yes, it is there in the root) it still gives me this error:

java.io.FileNotFoundException: file:\Z:\_JAVA_\MyProject_0_018\dist\bin\myjar.jar\someFile.obj <The filename, directory name, or volume label syntax is incorrect>

我100%确定文件名正确,并且也将其放置在jar文件的根目录中.

And I am 100% sure the name of the file is correct, also its placement in the root of my jar file.

还是它实际上认为myjar.jar是目录?

Or does it actually thinks that myjar.jar is a directory?

我正拼命寻找解决此路径字符串"混乱的方法.

I am desperately trying to find a solution to this "path string" mess.

推荐答案

您的保护域的代码源位置可能未返回您期望的位置.

Your protection domain's code source location likely returns not what you'd expect it to.

您应该像这样直接使用getResource(name):

You should use getResource(name) directly, like this:

URL locator = MyClass.class.getResource("someFile.obj");
api.parameter("filename", locator.toString());

这篇关于JAVA getResourceAsStream()文件的真实路径字符串解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 20:16