3

所以我有这个简单的代码:

public class FooBar {
    public static void main(String[] args) {
        String foo = "ğ";
        System.out.println(foo.getBytes().length);
    }
}

让我编译并运行它:

$ javac FooBar.java
$ java -Dfile.encoding=UTF-32 FooBar
4

好的,我对一个字符在一个字符串中占用 4 个字节并不感到惊讶,因为我告诉 Java 在运行程序时使用 UTF-32 编码。

让我们尝试使用 UTF-8 编码运行程序:

$ java -Dfile.encoding=UTF-8 FooBar
2

一切似乎都很好。

现在类文件 (FooBar.class) 是451 bytes。我将像这样更改代码:

public class FooBar {
    public static void main(String[] args) {
        String foo = "ğğ";
        System.out.println(foo.getBytes().length);
    }
}

再次编译,看到我磁盘中文件的长度为:453 bytes

显然,文件本身是以 UTF-8 编码存储在磁盘中的。如果我现在使用 UTF-32 编码运行这个 .class 文件:

$ java -Dfile.encoding=UTF-32 FooBar
8

一切似乎都很好,但是,无论如何告诉编译器使用 UTF-32 对字符串字符编码 .class 文件?

4

1 回答 1

3

系统属性file.encoding确定默认字符集,但编译器不使用。

Java 类文件具有已定义的二进制数据结构,无法更改(除非您编写自己的编译器和类加载器)。

因此常量池中字符串的编码总是被修改为 UTF-8

于 2016-01-21T11:16:19.723 回答