JavaFX - `isDirectory` Not Returning TRUE

十年热恋 提交于 2019-12-12 05:28:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!