[英]JAVA getResourceAsStream() real path string interpretation of a file
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: 我正在使用NetBeans 8.0.2(我知道已经有v8.2,但是对我来说有很多错误,所以我又回到了v8.0.2),并且我需要一个指向.obj文件的字符串路径来获取参数属性,例如这个:
api.parameter("filename", "obj/someFile.obj");
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: 上面的示例在我的应用程序的早期版本中起作用,在该应用程序中,我将.obj文件放置在与.jar文件位于同一目录中的名为“ obj”的文件夹中,但是现在,我想将其包含在JAR本身中,码:
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");
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: 因此,在对StackOverflow进行了一些摆弄之后,我发现了一些代码,我认为它们实际上可以使我直接将该路径作为字符串放置:
URL jar = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
api.parameter("filename", jar + "/someFile.obj");
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: 但是令人惊讶的是,尽管我多次检查该文件是否确实存在于我的内置jar文件中(是的,它在根目录中),但仍然给我这个错误:
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>
And I am 100% sure the name of the file is correct, also its placement in the root of my jar file. 而且我100%确信文件名正确,并且也将其放置在jar文件的根目录中。
Or does it actually thinks that myjar.jar
is a directory? 还是实际上认为
myjar.jar
是目录?
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. 您的保护域的代码源位置可能不会返回您期望的位置。
You should use getResource(name)
directly, like this: 您应该直接使用
getResource(name)
,如下所示:
URL locator = MyClass.class.getResource("someFile.obj");
api.parameter("filename", locator.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.