【问题标题】:How to specify the path correctly to open a file from a sub directory of my project?如何正确指定路径以从我的项目的子目录中打开文件?
【发布时间】:2019-10-06 04:28:37
【问题描述】:

我的项目结构是这样的

--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)

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

【问题讨论】:

    标签: java resources subdirectory


    【解决方案1】:

    @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());
    

    确保您的资源目录被标记为资源目录。

    【讨论】:

    • 我建议不要复制粘贴代码,帮助提出问题的用户正确回答与他/她的代码相关的问题。这只是一个建议。
    • 是的,你可以。但是您可能需要在saves 之前添加一个斜杠,这意味着/saves/xy.json 是路径。
    • 好的,我试过了,在 IDE 中它可以工作,但是当我尝试使用 .jar 时,我有 Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
    • 对,创建jar时不能使用URI。试试这个:stackoverflow.com/questions/10144210/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多