[英]Can't open file using .getResource().getPath()
One year ago I've wrote JavaFX 2.0 application for my graduation work. 一年前,我为毕业工作编写了JavaFX 2.0应用程序。 But after one year pass I have a problem with code, that worked before.
但是经过一年之后,我遇到了以前使用过的代码问题。
So, in code I want to get folder and list it's files: 因此,在代码中,我想获取文件夹并列出其文件:
File dir = new File(getClass().getResource("media/images/backgrounds/").getPath());
File[] files = dir.listFiles();
for (File file : files) {
list.add(file.toURI().toString());
}
and I'm getting java.lang.NullPointerException on line "for (File file : files) {" 并且我在“ for(File file:files){”行上获取java.lang.NullPointerException
System.out.print(getClass().getResource("media/images/backgrounds/").getPath());
returns file:/D:/JavafxApp1/JavafxApp/dist/run2054723721/JavafxApp.jar!/javafxapp/media/images/backgrounds/ 返回文件:/ D:/JavafxApp1/JavafxApp/dist/run2054723721/JavafxApp.jar!/ javafxapp / media / images / backgrounds /
I don't want make another method for reading files from stream from JAR file.This method of getting files have worked 100% one year ago, but why it doesn't work now? 我不想使用另一种方法来从JAR文件中读取流中的文件。这种获取文件的方法一年前已100%起作用,但是为什么现在不起作用? Thanks!
谢谢!
It won't work because your folder is in a jar. 因为您的文件夹在罐子里,所以它不起作用。 I suppose one year ago they were not.
我想一年前还没有。 I think you don't need to have seperate code for the case where the directory is outside of a jar:
我认为对于目录在jar之外的情况,您不需要使用单独的代码:
I found this example that shows how you can list the files of a directory using getResourceAsStream. 我发现此示例显示了如何使用getResourceAsStream列出目录的文件。 Then, in turn, you could access these resources by getResourceAsStream.
然后,您可以依次通过getResourceAsStream访问这些资源。 You will never know whether you were inside or outside a jar :-)
您永远不会知道您是在罐子里还是在罐子里:-)
Don't create a File
it won't work for accessing resources inside jar. 不要创建一个
File
,它将不能访问jar中的资源。
getClass().getResource()
already returns you URL
, so use that URL or another option is getResourceAsStream()
已经返回了您的
URL
,因此使用该URL或另一个选项是getResourceAsStream()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.