问题
Why is this check not return true?
String dirpath = getClass().getResource("../util/assets/sounds/").toString();
File dir = new File(dirpath);
System.out.println(dirpath);
System.out.println(dir);
System.out.println(dir.isDirectory());
It returns these:
file:/D:/JAVA/exercises/FX/TasksList/build/classes/taskslist/util/assets/sounds
file:\D:\JAVA\exercises\FX\TasksList\build\classes\taskslist\util\assets\sounds
false
I run it using netbeans IDE as a source code.
回答1:
getClass().getResource(...) returns a URL, not a file path string. A file path string is needed by the constructor of File.
You can try using the Paths constructor to construct a valid file path from a URI, which you can get from the resource using toUri().
So, this should work:
Files.isDirectory(
Paths.get(
getClass().getResource("../util/assets/sounds/").toUri()
)
)
Or
new File(
getClass().getResource("../util/assets/sounds/").toUri()
).isDirectory();
I haven't got a windows machine to try that on.
Note: If you start packaging your app as jar (as is recommended), then this technique will break. The resource would not be a file, but instead a jar resource. There is no concept of a file directory in relation to a jar resource.
回答2:
It supposed to be :
String dirpath = getClass().getResource("../util/assets/sounds/").getPath();
instead of:
String dirpath = getClass().getResource("../util/assets/sounds/").toString();
And it will work.
来源:https://stackoverflow.com/questions/45292932/javafx-isdirectory-not-returning-true