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).

Prerequisite

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.

  1. 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();
         }
     }
    
  2. Download the fortunes.u8 resource file and save it in the same directory as Fortune.java.

  3. Compile the Java source code:
     $JAVA_HOME/bin/javac Fortune.java
    
  4. Build a native executable by specifying the resource path:
     $JAVA_HOME/bin/native-image Fortune -H:IncludeResources=".*u8$"
    
  5. Run the executable:
     ./fortune