How do I use Java getResource() to get a resource from a parent directory?

不问归期 提交于 2020-01-11 08:15:27

问题


I've tried numerous methods now, including FilenameUtils.normalize() from commons IO, but I can't seem to be able to get a resource in another folder to get a Java FXML file.

The code is the following

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

Where the desired FXML file is:

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

How do I best get the desired file's URL?

Thank you!


回答1:


You can get resources relative to the Class or the context root. In your example putting / at the start of the string if thats your package structure in your application. Try

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



回答2:


It seems to me that if we use .getResource only when searching in marked as resource folder. Otherwise, even if folder path is correct, but it's not marked as resource folder we'll got an error. So, I do this way:

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


来源:https://stackoverflow.com/questions/14389731/how-do-i-use-java-getresource-to-get-a-resource-from-a-parent-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!