Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

path

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!

like image 208
calben Avatar asked Jan 17 '13 23:01

calben


People also ask

How to get files from resources folder Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How does getResource work in Java?

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.

How to get path to resources in Java?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.


1 Answers

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")
like image 152
Alex Edwards Avatar answered Oct 07 '22 19:10

Alex Edwards