不,没有切实可行的方法来改变它.例如,在OpenJDK中,file.encoding当虚拟机启动时,会从系统属性中读取默认字符集,并将其存储在Charset类中的私有静态字段中.如果需要使用不同的编码,则应使用允许指定编码的类.
您可以通过反射改变私人领域来破解你的方式.如果您确实没有其他选择,那么您可以尝试这种方法.您将代码定位到特定JVM的特定版本,并且它可能不适用于其他JVM.这是在当前版本的OpenJDK中更改默认字符集的方法:
import java.nio.charset.Charset;
import java.lang.reflect.*;
public class test {
public static void main(String[] args) throws Exception {
System.out.println(Charset.defaultCharset());
magic("latin2");
System.out.println(Charset.defaultCharset());
}
private static void magic(String s) throws Exception {
Class<Charset> c = Charset.class;
Field defaultCharsetField = c.getDeclaredField("defaultCharset");
defaultCharsetField.setAccessible(true);
defaultCharsetField.set(null, Charset.forName(s));
// now open System.out and System.err with the new charset, if needed
}
}
Run Code Online (Sandbox Code Playgroud)