【发布时间】:2015-08-12 20:15:59
【问题描述】:
您知道为什么下面的第一行和第二行不生成文件的 BOM 而第三行生成吗?我认为 UTF-16LE 是正确的编码名称,并且该编码不会自动创建 BOM 到文件的开头。
new File("foo-wo-bom.txt").withPrintWriter("utf-16le") {it << "test"}
new File("foo-bom1.txt").withPrintWriter("UnicodeLittleUnmarked") {it << "test"}
new File("foo-bom.txt").withPrintWriter("UTF-16LE") {it << "test"}
另一个样本
new File("foo-bom.txt").withPrintWriter("UTF-16LE") {it << "test"}
new File("foo-bom.txt").getBytes().each {System.out.format("%02x ", it)}
打印
ff fe 74 00 65 00 73 00 74 00
和java
PrintWriter w = new PrintWriter("foo.txt","UTF-16LE");
w.print("test");
w.close();
FileInputStream r = new FileInputStream("foo.txt");
int c;
while ((c = r.read()) != -1) {
System.out.format("%02x ",c);
}
r.close();
打印
74 00 65 00 73 00 74 00
Java 不会产生 BOM,而 Groovy 会产生 BOM。
【问题讨论】:
-
欢迎来到 StackOverflow。我认为字符集不区分大小写(它应该在 Java 中),但没有任何文档可以确认,我只能假设
utf-16le(小写)告诉withPrintWriter()不要发出 BOM,@987654328 @(大写)告诉它发出一个 BOM。这是此示例中的唯一区别。UnicodeLittleUnmarked强制跳过 BOM,UnicodeLittle强制跳过 BOM,但也许utf-16le/UTF16-LE在 Groovy 中更模糊? -
我也使用 Java 和 PrintWriter 进行了测试,这些编码都不会产生 BOM。我认为这是正确的。如果我定义为 LE 或 BE。无需设置 BOM。如果我只使用 UTF-16,Java 用 Little Endian 写入文件,并且还有 BOM 在 groovy 中似乎 utf-16 和 UTF-16 产生 BOM。