首页 > 解决方案 > 如何在同一个项目中找到文件的路径?

问题描述

我有 java fx 应用程序,我将它从纯 java 项目迁移到 maven,现在我的 .fxml 文件的路径有问题。正如您在下面看到的,我需要 Main.java 中的 sample.fxml。我尝试了不同的路径,但没有任何效果。你能看看吗?

在此处输入图像描述

这是我尝试过的:

    System.out.println(getClass().getResource("src/main/java/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResource("/java/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResource("sample/fxml/sample.fxml"));
    System.out.println(getClass().getResource("/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResource("fxml/sample.fxml"));
    System.out.println(getClass().getResource("sample.fxml"));

    System.out.println(getClass().getResourceAsStream("src/main/java/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResourceAsStream("/java/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResourceAsStream("sample/fxml/sample.fxml"));
    System.out.println(getClass().getResourceAsStream("/sample/fxml/sample.fxml"));
    System.out.println(getClass().getResourceAsStream("fxml/sample.fxml"));
    System.out.println(getClass().getResourceAsStream("sample.fxml"));

这些中的每一个都返回null。

标签: javamavenfileintellij-idea

解决方案


我找到了答案。

Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

当我们将 sample.fxml 移动到资源文件夹时正在工作。


推荐阅读