Home / Java Patterns and Pitfalls     frequal.com

Bundle Resources in a TeaVM/Flavour App

In a TeaVM single-page app, you may want to access files bundled with the app. For CSS and images, you can include them in your app HTML normally and let the browser fetch them. But in other cases you may have a data file or configuration file you want bundled with the app so you can read it from your code. This article shows how you can include it like you would resources in a normal app, with one extra step.

We will show how to add a properties file called config.properties to your TeaVM app.

Resource Placement

Place the config.properties file in the src/main/resources folder, as usual.

List Resources to Include in a ResourceSupplier

ResourceSupplier is a TeaVM interface you need to implement to return the names of resources to be bundled in your app. First, implement the ResourceSupplier interface. Then place the fully-qualified name of the class in a file called resources/META-INF/org.teavm.classlib.ResourceSupplier.

For our config.properties file, you would implement ResourceSupplier's supplyResources() method as follows:

  public String[] supplyResources(ResourceSupplierContext context) {
    String[] result = { "config.properties" };
    return result;
  }

Reading the Resource

This is the easy part. Get the class loader, then get a resource as a stream, like on a traditional JVM. You must use one of the files you returned from the ResourceSupplier. Other files are not bundled into the JS file built by TeaVM.
    InputStream stream = MyClass.getClassLoader().getResourceAsStream("config.properties");

Last modified on 12 Mar 2021 by AO

Copyright © 2021 Andrew Oliver