如何正确指定从项目子目录打开文件的路径?

时间:2019-05-19 17:05:43

标签: java resources subdirectory

我的项目结构是这样的

-src

--------------资源

--------------保存

我多次使用此子文件夹:

 File tempFile = new File("src/saves/" + videoName + ".json");

或有时这样:

ImageView icon = new ImageView("resources/edit.png");

和:

File f = new File("src/resources/zelda.mp4");

由于某些原因,它在icon下有效,但不适用于视频/文件,当我尝试出现此错误时:

Caused by: MediaException: MEDIA_UNAVAILABLE : C:\Users\histackoverflow\IdeaProjects\project2\resources\zelda.mp4 (specified path can't be found)

所以我想知道使用路径的方式有什么问题吗?

1 个答案:

答案 0 :(得分:0)

@Edit:此功能适用于在IDE中引用文件。对于jar中适当的文件引用,请遵循以下命令:Java Jar file: use resource errors: URI is not hierarchical

我不建议在路径中输入字符串。加载文件的一种更好的方法是将它们放入资源库中(您已经这样做了),并通过类引用调用资源库并从中获取URI:

    InputStream file = new FileInputStream(getClass().getResource("/edit.png").getPath());
    Image image = new Image(file);
    ImageView icon = new ImageView(image);


    File f = new File(getClass().getResource("/zelda.mp4").toURI());

确保将包含资源的目录标记为资源目录。