Search code examples
javalocalizationgradleresourcebundle

Include a file multiple times with different names in a Gradle-built JAR


I work with Java resource bundles that are included in the final JAR using the standard resource processing provided by the java plugin. The file structure is the following:

src
└── main
    ├── java
    └── resources
        ├── com
        │   └── example
        │       └── lang
        │           ├── localization.properties
        │           └── localization_en.properties
        └── folder-with-unrelated-resources

Due to the nature of the automatic resource loading, I need to include the English file two times: As the standard English file (localization_en.properties) and as the base file that provides a fallback if a more specific localization is not found (localization.properties). At the moment, both of these files are present in the resource directory, even through their content is exactly the same.

I am looking for a way that let Gradle duplicate the present localization_en.properties and include it with the base name, so I do not need two separated files in the resource directory. I assume I need to hook into the ProcessResources task, but I have no idea on how to create the duplicate of the localization_en.properties file and add it to the processed resources.


Solution

  • Here's how you copy the resources with gradle:

    task copyLocalizations(type: Copy) {
        from('src/main/resources')
        into(sourceSets.main.output.resourcesDir)
        include('localization.properties')
        rename('localization.properties', 'localization_en.properties')
    }
    
    processResources.dependsOn(copyLocalizations)
    

    But I think there is an even better way to overcome the JVM defaults -> set the default locale programmatically (eg. to the ROOT locale):

    Locale.setDefault(Locale.ROOT);
    

    Therefore your application would be independent to environment configs (and in general more robust).