Search code examples
javainternationalizationresourcebundle

What is the syntax for accessing internationalization resource bundles inside a package in Java?


I'm looking for help on internationalization of a Java app in semeru-18 SDK in IntelliJ 2023.1

Following tutorials and others (only utilizing the default package for all internationalizations), I've added a resource bundle for Java in my favorite IDE and attempted to load it for internationalized strings.

static ResourceBundle messages = ResourceBundle.getBundle("<Program>Strings", Locale.getDefault());

java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle Exception

The output directory has the app launching with the bundle at the root of the class directory, but the IDE uses a 'resources' tag preset in some, but not all examples. Also an error.

Shifting back to repeating the demo, I move the Java file to the root directory.

ResourceBundle messages = ResourceBundle.getBundle("<Program>Strings", Locale.getDefault());
System.out.println("ProgramName");

The output duplicates the demo. Creating parallel resource files in the resources directory mirroring my package directory structure for every package I now get the error

java.util.MissingResourceException: Can't find bundle for base name ProgramStrings, locale en_US

though the resource is present, confirmed checking the target directory manually with a file editor.

I have multiple packages types with only a few per item and want the convenience of a global translatable file and using packages are essential. Assuming the problem is the resource path is relative to the current package, what is the syntax to correct the difference in accessing a resource bundle between my relative package location/resource file location and the default package tutorial?

The same error occurs when placing the resource in the source directory, but the resource files are not copied across to the target folder and have to be inserted manually in that case.


Solution

  • Using resource classes:

    • Default: src/main/java/my/app/MyResources.java
      • class MyResources extends ResourceBundle
    • English: src/main/java/my/app/MyResources_en.java
      • class MyResources_en extends MyResources
    • French: src/main/java/my/app/MyResources_fr.java
      • class MyResources_fr extends MyResources
    • German: src/main/java/my/app/MyResources_de.java
      • class MyResources_de extends MyResources

    Using property files:

    • Default: src/main/resources/my/app/MyResources.properties
    • English: src/main/resources/my/app/MyResources_en.properties
    • French: src/main/resources/my/app/MyResources_fr.properties
    • German: src/main/resources/my/app/MyResources_de.properties

    And then reference it with the fully qualified resource name in your code ResourceBundle.getBundle("my.app.MyResources");. The default Locale will be used.