Search code examples
javaandroidjavafxclassloader

Alternative to java.nio.file.Paths in Java6


Since the java.nio.file.Paths class and its package do not exist in Java6 and Android, I was wondering how I could use an alternative method for Paths.get("filename").toUri().toURL()? I try to load a fxml file using the FXMLLoader in JavaFX. Usually I put all fxml-files in a specific layout-package within the src directory, which makes it easy to load these files via relative path. However, because I build the JavaFX project for Android, I need to store the fxml-file into the assets directory so that it will automatically included in the apk file (using gradle build).

This is my project structure so far:

MyProject
-- src\main\java\somepackage\Main.java
-- assets\sample_layout.fxml

However, when I build the apk, the structure looks like this:

Content of MyProject.apk
-- assets\sample_layout.fxml
-- classes.dex // which contains all compiled classes
   -- somepackage\Main.java

I need to access the sample_layout.fxml within the assets directory from the Main.java. Any idea how I can do that?

Here is what is working on Java7, but not for Java6 (and not on Android since the Paths class is not available in Java6):

URL myFxmlLayout= Paths.get("assets/sample_layout.fxml").toUri().toURL();
FXMLLoader loader = new FXMLLoader(myFxmlLayout);
AnchorPane page = (AnchorPane) loader.load();

For Java6 I tried the following, which is not working:

URL myFxmlLayout= new URI("file:///assets/sample_layout.fxml").toURL();
// OR
URL myFxmlLayout= new URI("file:///../../../../assets/sample_layout.fxml").toURL();

Hope you can help me.

Best regards, Michael


Solution

  • In fact the usage of Paths was design-technically wrong to begin with. The FXML source might better be packed in a jar as a read-only resource.

    MyProject
    -- src\main\java\somepackage\Main.java
    -- src\main\resources\assets\sample_layout.fxml
    
    URL myFxmlLayout= Main.class.getResource("/assets/sample_layout.fxml");
    

    In your original design, you could use new File(...) instead, but then have to take care of the path to assets (getAbsolutePath), and the runtime installation of it.