【问题标题】:How do I use Java getResource() to get a resource from a parent directory?如何使用 Java getResource() 从父目录获取资源?
【发布时间】:2013-01-01 14:53:56
【问题描述】:

我现在尝试了很多方法,包括来自 commons IO 的 FilenameUtils.normalize(),但我似乎无法在另一个文件夹中获取资源来获取 Java FXML 文件。

代码如下

  try {
     root = FXMLLoader.load(getClass().getResource("../plugin/PluginSelection.fxml"));
  } catch (IOException ex) {
     Logger.getLogger(QueueOperationsController.class.getName()).log(Level.SEVERE, null, ex);
  }

所需的 FXML 文件在哪里:

gui
   dialogues
      plugins
         PluginSelection.fxml // desired file
      dataset
         QueueOperationsController // current class

如何最好地获取所需文件的 URL?

谢谢!

【问题讨论】:

  • plugin 文件夹在哪里?
  • 您的文件树显示了一个名为 plugin 的目录,但您的代码示例引用了一个名为 plugins 的目录。会不会是这个问题?
  • (getClass().getResource("../plugin/PluginSelection.fxml"));为我工作

标签: java path


【解决方案1】:

您可以获得与Class 或上下文根相关的资源。在您的示例中,如果那是您的应用程序中的包结构,则将 / 放在字符串的开头。试试

getClass().getResource("/gui/dialogues/plugins/PluginSelection.fxml")

【讨论】:

  • 将其更改为:root = FXMLLoader.load(getClass().getResource("/pdpro/gui/dialogues/plugin/PluginSelection.fxml"));它就像一个魅力。谢谢!
  • 如果我的资源比类(../../../../resource)高四个目录,我是否只需键入////resource
【解决方案2】:

在我看来,如果我们仅在标记为资源文件夹中搜索时使用 .getResource。否则,即使文件夹路径正确,但没有标记为资源文件夹,也会出错。 所以,我这样做:

FileInputStream fileInputStream = new FileInputStream(new File("src/main/java/CRUD/bnkseekCRUD.fxml"));
    Parent root = loader.load(fileInputStream);

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 2019-03-12
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多