Christian Rädel
Christian Rädel

Reputation: 591

How to automatically escape unicode characters in Java property files using Gradle?

I'm translating a Java application by using a ResourceBundle with various *.properties files. Now I like to have a Gradle task or want to modify a task to automatically escape any unicode character by replacing it with its ASCII representation, something like Java's native2ascii tool does.

This is what I'm done so far with my build file, but the output remains unescaped:

import org.apache.tools.ant.filters.EscapeUnicode

tasks.withType(ProcessResources) {
    filesMatching('**/*.properties') {
        println "\t-> ${it}"
        filter EscapeUnicode
    }
}

Any help is appreciated.

Upvotes: 8

Views: 1338

Answers (2)

Mathieu
Mathieu

Reputation: 746

The solution given by stanislav caused me duplicate file conflicts (I think this creates a new "pipeline" from the same source files, only including 'properties' files, filtering, and writing to the same dir as the original task, but the original "pipelines" of the task stay unchanged).

For anyone looking to do this without duplication, here is my solution. It is also using Native2AsciiFilter instead of EscapeUnicode which should give a more similar result to native2ascii maven tool. This filter works on lines and not on files (it does not extend java.io.FilterReader), so we can't use it directly as a parameter of filter.

import org.apache.tools.ant.filters.Native2AsciiFilter
tasks.withType(ProcessResources).each { task ->
    def nativeToAscii = new Native2AsciiFilter()
    task.filesMatching('**/*.properties') {
        filter { line -> nativeToAscii.filter(line) }
    }
}

Upvotes: 1

Stanislav
Stanislav

Reputation: 28126

You can do it providing the additional copy specification for properties files, this way:

import org.apache.tools.ant.filters.EscapeUnicode
tasks.withType(ProcessResources).each { task ->
    task.from(task.getSource()) {
        include '**/*.properties'
        filter(EscapeUnicode)
    }
}

Upvotes: 7

Related Questions