◀Back
Include Resources in a Native Executable
The following steps illustrate how to include a resource in a native executable. The application fortune
simulates the traditional fortune
Unix program (for more information, see fortune).
-
Make sure you have installed a GraalVM JDK. The easiest way to get started is with SDKMAN!. For other installation options, visit the Downloads section.
-
Save the following Java source code as a file named Fortune.java:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class Fortune { private static final String SEPARATOR = "%"; private static final Random RANDOM = new Random(); private ArrayList<String> fortunes = new ArrayList<>(); public Fortune(String path) { // Scan the file into the array of fortunes Scanner s = new Scanner(new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(path)))); s.useDelimiter(SEPARATOR); while (s.hasNext()) { fortunes.add(s.next()); } } private void printRandomFortune() throws InterruptedException { int r = RANDOM.nextInt(fortunes.size()); //Pick a random number String f = fortunes.get(r); //Use the random number to pick a random fortune for (char c: f.toCharArray()) { // Print out the fortune System.out.print(c); Thread.sleep(100); } } public static void main(String[] args) throws InterruptedException { Fortune fortune = new Fortune("/fortunes.u8"); fortune.printRandomFortune(); } }
-
Download the fortunes.u8 resource file and save it in the same directory as Fortune.java.
- Compile the Java source code:
$JAVA_HOME/bin/javac Fortune.java
- Build a native executable by specifying the resource path:
$JAVA_HOME/bin/native-image Fortune -H:IncludeResources=".*u8$"
- Run the executable image:
./fortune