Search code examples
graalvmgraalvm-native-imagegluonfx

Get directory of compiled native image by GraalVM at runtime


I compiled my Java application with (GluonFX which itself uses) GraalVM. How can I get the directory where my application binary resides at runtime? (not the users working directory)

  • Before using GraalVMs native-image tool, I used to read System.getProperty("java.home") and deduced it from there. But this system property does not exist anymore.
  • I tried to find another system property, but the directory of my application was in none.
  • I tried to read environment variables and found System.getenv("_"), but as "_ contains the last program run", this does not feel stable.
  • I tried to resolve Paths.get(".").toAbsolutePath() but this only returned the current working directory.

My end goal is to package this small application binary in a bigger application and this small application should call other applications which will get packaged next to it.


Solution

  • You can get the running path from java code like below

    Path path = Path.of(
            Main.class.getProtectionDomain()
                    .getCodeSource()
                    .getLocation()
                    .toURI()
    ).getParent();
    System.out.println(path);
    

    Please change the Main class to the class you use in your code.

    There is another way too but that requires nativeimage dependency.

    <dependency>
        <groupId>org.graalvm.nativeimage</groupId>
        <artifactId>library-support</artifactId>
        <version>23.0.1</version>
        <scope>provided</scope>
    </dependency>
    

    then call it like below

    System.out.println("exe path:"+ProcessProperties.getExecutableName());
    

    example output

    oz-mint@ozmint-MACH-WX9:~/Downloads/my-gluon-application$ ./target/gluonfx/x86_64-linux/My\ Gluon\ Application 
    exe path:/home/oz-mint/Downloads/my-gluon-application/target/gluonfx/x86_64-linux/My Gluon Application
    Dec 30, 2023 3:22:52 PM com.sun.javafx.application.PlatformImpl startup
    WARNING: Unsupported JavaFX configuration: classes were loaded from 'unnamed module @71c7db30'
    Dec 30, 2023 3:22:53 PM com.gluonhq.attach.util.Platform <clinit>
    INFO: [Gluon Attach] System Property javafx.platform is not defined. Platform will be set to Platform.DESKTOP
    

    working example

    References