maven file.encoding和Charset.defaultCharset()

maven file.encoding和Charset.defaultCharset(),maven,encoding,Maven,Encoding,我的maven父母POM包含 <file.encoding>UTF-8</file.encoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 当我运行mvn-Dfile.encod

我的maven父母POM包含

<file.encoding>UTF-8</file.encoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
当我运行mvn-Dfile.encoding=UTF-8清洁测试时,输出为:

------------------UTF-8
Byte count: 1
fc
------------------windows-1252
现在我有两个问题:

1) 我的POM中的属性有什么用

2) 当我指定-Dfile.encoding=UTF-8时,为什么默认的字符集没有更改为UTF-8(因此getBytes()仍然使用“cp1252”并返回1个字节),我如何更改它

提前感谢,


罗纳德

编辑也必须设置相同的编码。显然,您已将该文件保存在Cp1252中。使用JEdit或记事本++检查

getBytes("UTF-8"); // 2
getBytes("Cp1252"); // 1
getBytes(); // Depending on platform, System.getProperty("file.encoding")

maven如何处理这些属性,我不能完全确定在
file.encoding

的情况下,如果您想让Charset.defaultCharset返回UTF-8,您还需要为插件argLine设置它,因为如果您只在属性中指定它,就太晚了

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
      <skipTests>${skip.unit.tests}</skipTests>
      <enableAssertions>true</enableAssertions>
      <argLine>${surefireArgLine} -Dfile.encoding=UTF-8</argLine>
    </configuration>
  </plugin>

org.apache.maven.plugins
maven surefire插件
2.19.1
${skip.unit.tests}
真的
${surefireArgLine}-Dfile.encoding=UTF-8

Hi Joop,Java源文件已保存为UTF-8。此外,它也无法解释为什么对Charset.defaultCharset()的调用在第二个结果中仍然返回“windows-1252”。我猜默认字符集是“ü”的主要原因。getBytes()返回1字节。如果默认字符集是UTF-8,它将返回2个字节——就像我调用“ü”.getBytes(“UTF-8”)时一样。我已经扩展了答案。您好,Joop,我同意您粘贴的代码。特别是第3行是相关的-getBytes()使用默认的平台字符集。但这并不能回答我的问题。真正的问题是为什么Charset.defaultCharset()在我指定-Dfile.encoding=UTF-8之后仍然返回“Cp1252”,而getBytes()仍然使用“Cp1252”。
Charset.defaultCharset()查看初始为空的静态字段。第一次尝试属性
file.encoding
,否则为UTF-8。接下来的时间,它产生静态场。因此,maven调用
Charset.defaultCharset()
肯定太早了。嗨,Joop,这就是查看OpenJDK源代码时的样子。但这意味着当您有一个类只包含一个带有System.out.println(Charset.defaultCharset())的main方法时;并且不要指定-Dfile.encoding,它将返回UTF-8。如果我在我的机器上尝试,它仍然返回“windows-1252”。我使用的是Oracle JDK“1.7.0_07”。
getBytes("UTF-8"); // 2
getBytes("Cp1252"); // 1
getBytes(); // Depending on platform, System.getProperty("file.encoding")
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
      <skipTests>${skip.unit.tests}</skipTests>
      <enableAssertions>true</enableAssertions>
      <argLine>${surefireArgLine} -Dfile.encoding=UTF-8</argLine>
    </configuration>
  </plugin>