【问题标题】:Why does my text normalization behave differently in different environments?为什么我的文本规范化在不同的环境中表现不同?
【发布时间】:2017-11-13 09:10:20
【问题描述】:

我正在使用来自this answer 的以下方法/代码对一些重音文本进行规范化

重音去除:

String accented = "árvíztűrő tükörfúrógép";
String normalized = Normalizer.normalize(accented,  Normalizer.Form.NFD);
normalized = normalized.replaceAll("[^\\p{ASCII}]", "");
System.out.println(normalized);

当我使用 IntelliJ 运行它时(作为单元测试的一部分),这给出了预期的结果:

arvizturo tukorfurogep

如果我从命令行(通过 gradle)运行它,我会得到:

ArvAztArA tAkArfArAgA

在这两种情况下,我都使用同一台 PC 和 Java 1.8.0_151

相关部分来自build.gradle

apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
  testCompile group: 'junit', name: 'junit', version: '4.12'
}

是什么导致了这种不同的行为?以及如何确保在任何地方都能获得预期的结果?

【问题讨论】:

  • 能否请您分享您的 gradle 文件,因为我使用 gradle 尝试了相同的代码,它有效。
  • 问题更新为gradlesn-p。
  • 你的 gradle 中的运行任务在哪里?,你使用 gradle 中的任务运行代码,就像这样:task(runui, dependsOn: 'classes', type: JavaExec) { main = 'stockticker. ui.StockTickerDriver' 类路径 = sourceSets.main.runtimeClasspath }
  • 在命令行输入gradle clean test
  • 想象一下,看起来更像是编译问题而不是运行时问题。定义您的源编码(或仅在源代码中使用 Unicode 转义和 ascii)

标签: java string unicode-normalization


【解决方案1】:

感谢@eckes 和其他人的编译时间建议。通过在编译时指定编码,我能够得到想要的结果。

我添加到build.gradle 的设置是:

compileTestJava.options.encoding = 'UTF-8'

此选项仅影响测试类(​​这是我的问题所在)。您还可以使用:

compileJava.options.encoding = 'UTF-8'

如果您的生产代码中有需要编码的文本。

我遇到的另一种解决方案是:

tasks.withType(JavaCompile) {
  options.encoding = 'UTF-8'
}

(有趣的是,上述解决方案都没有改变file.encoding系统属性的值。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2018-11-08
    • 2016-06-05
    • 2014-08-08
    • 2021-11-13
    相关资源
    最近更新 更多