如何正确指定路径以从我的项目的子目录中打开文件?
How to specify the path correctly to open a file from a sub directory of my project?
我的项目结构是这样的
--来源
----------------资源
----------------节省
我多次使用此子文件夹,如下所示:
File tempFile = new File("src/saves/" + videoName + ".json");
或者有时像这样:
ImageView icon = new ImageView("resources/edit.png");
和:
File f = new File("src/resources/zelda.mp4");
由于某些原因,它适用于 icon
但不适用于 video/file,当我尝试时出现此错误:
Caused by: MediaException: MEDIA_UNAVAILABLE : C:\Users\hiWhosebug\IdeaProjects\project2\resources\zelda.mp4 (specified path can't be found)
所以我想知道我使用路径的方式有什么问题?
@Edit:这适用于引用 IDE 中的文件。对于 jar 中的适当文件引用,请遵循以下内容:Java Jar file: use resource errors: URI is not hierarchical
我不建议将路径作为字符串键入。加载文件的更好方法是将它们放入资源中(您已经这样做了)并通过 class 引用调用资源并从中获取 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());
确保您的资源目录被标记为资源目录。
我的项目结构是这样的
--来源
----------------资源
----------------节省
我多次使用此子文件夹,如下所示:
File tempFile = new File("src/saves/" + videoName + ".json");
或者有时像这样:
ImageView icon = new ImageView("resources/edit.png");
和:
File f = new File("src/resources/zelda.mp4");
由于某些原因,它适用于 icon
但不适用于 video/file,当我尝试时出现此错误:
Caused by: MediaException: MEDIA_UNAVAILABLE : C:\Users\hiWhosebug\IdeaProjects\project2\resources\zelda.mp4 (specified path can't be found)
所以我想知道我使用路径的方式有什么问题?
@Edit:这适用于引用 IDE 中的文件。对于 jar 中的适当文件引用,请遵循以下内容:Java Jar file: use resource errors: URI is not hierarchical
我不建议将路径作为字符串键入。加载文件的更好方法是将它们放入资源中(您已经这样做了)并通过 class 引用调用资源并从中获取 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());
确保您的资源目录被标记为资源目录。