Search code examples
gradlebuild.gradlefile-encodings

Transcoding with Gradle


My build.gradle file generates UNIX and Windows launcher scripts for my Java project from templates. Templates are UTF-8 encoded and the generated scripts are UTF-8 too. It's not a problem on Linux where UTF-8 support is ubiquitous, but Windows has some issues displaying non Latin-1 characters in cmd.exe terminal window. After reading Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10) I come to a conclusion that converting the generated UTF-8 script to cp1250 (in my case) would save me lots of trouble when displaying hungarian text. However I couldn't figure out how to convert a UTF-8 file to other code page (looked at copy, but didn't find a way to specify output encoding.)


Solution

  • Simply use FileUtils from Apache Commons IO in your build file.

    import org.apache.commons.io.FileUtils
    
    buildscript {
        repositories {
            mavenCentral()
        }
    
        dependencies {
            classpath("commons-io:commons-io:2.8.0")
        }
    }
    

    And then, in the relevant part of the script, where launcher scripts are generated :

    File f =  file('/path/to/windows-launcher')
    // Reading the content as UTF-8
    String content = FileUtils.readFileToString(f, 'UTF-8')
    // Rewriting the file as cp1250
    FileUtils.write(f, content, "cp1250")