【问题标题】:Gradle uses wrong encoding (Latin-1) for property fileGradle 对属性文件使用错误的编码 (Latin-1)
【发布时间】:2015-09-06 12:28:52
【问题描述】:

我尝试从带有变音符号的文件中读取属性,这是我的 build.gradle:

task utf8test << {

    Properties props = new Properties()
    def propFile = new File("my.property")
    if (propFile.canRead()) {
        props.load(new FileInputStream(propFile))
        for (Map.Entry property in props) {
                println property.value
        }
    }
}

我的属性文件看起来像(UTF-8 编码):

challenge: ö

如果我执行任务:gradle utf8test 结果看起来像

:utf8test
ö

BUILD SUCCESSFUL

Total time: 0.877 secs

“ö”改成“ö”,很容易理解。 “ö”作为十六进制是 c3b6 和 latin-1 中的 c3 是 à 而 b6 是 ¶,但这不是我所期望的。

问题:如何配置 gradle 以读取 UTF-8 编码的属性

更多信息:

如果我在 gradle 中打印出 propFiles 内容:

println propFile.text

我收到“ö”作为输出,因此文件被正确读取,并且输出被我的 shell 正确编码。

Gradle-daemon 运行:-Dfile.encoding=UTF-8

使用 -Dfile.encoding=UTF-8:gradle utf8test -Dfile.encoding=UTF-8 执行 gradle 没有帮助,export GRADLE_OPTS="-Dfile.encoding=UTF-8" 在 bash 中也没有帮助,将 systemProp.file.encoding=utf-8 添加到 gradle.properties 也没有帮助。

我在 gradle 中找不到 Properties-Class 的文档页面,有没有配置编码的选项?

到目前为止非常感谢!

【问题讨论】:

    标签: encoding utf-8 gradle latin1


    【解决方案1】:

    这是意料之中的,与 gradle 关系不大。 documentation of java.util.Properties(与 Gradle 无关,是 JDK 的标准类)明确指定属性文件的标准编码为 ISO-8859-1。如果你是唯一一个读取文件的人,并且希望它包含 UTF-8,那么明确地将其读取为 UTF-8:

    Properties props = new Properties()
    def propFile = new File("my.property")
    if (propFile.canRead()) {
        props.load(new InputStreamReader(new FileInputStream(propFile), StandardCharsets.UTF_8));
        for (Map.Entry property in props) {
                println property.value
        }
    }
    

    【讨论】:

    • 感谢您的完美回答!并将我链接到 java 文档!
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2017-09-28
    • 1970-01-01
    相关资源
    最近更新 更多