设置默认的 Java 字符编码 [英] Setting the default Java character encoding

查看:30
本文介绍了设置默认的 Java 字符编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式正确设置 JVM (1.5.x) 使用的默认字符编码?

How do I properly set the default character encoding used by the JVM (1.5.x) programmatically?

我读过 -Dfile.encoding=whatever 曾经是旧 JVM 的方法.我没有那种奢侈,因为我不会涉足.

I have read that -Dfile.encoding=whatever used to be the way to go for older JVMs. I don't have that luxury for reasons I wont get into.

我试过了:

System.setProperty("file.encoding", "UTF-8");

并且设置了属性,但它似乎不会导致下面的最终 getBytes 调用使用 UTF8:

And the property gets set, but it doesn't seem to cause the final getBytes call below to use UTF8:

System.setProperty("file.encoding", "UTF-8");

byte inbytes[] = new byte[1024];

FileInputStream fis = new FileInputStream("response.txt");
fis.read(inbytes);
FileOutputStream fos = new FileOutputStream("response-2.txt");
String in = new String(inbytes, "UTF8");
fos.write(in.getBytes());

推荐答案

不幸的是,必须在 JVM 启动时指定 file.encoding 属性;到您的主要方法被输入时,String.getBytes() 使用的字符编码以及 InputStreamReaderOutputStreamWriter 的默认构造函数已经永久缓存.

Unfortunately, the file.encoding property has to be specified as the JVM starts up; by the time your main method is entered, the character encoding used by String.getBytes() and the default constructors of InputStreamReader and OutputStreamWriter has been permanently cached.

正如 Edward Grech 指出的,在这样的特殊情况下,环境变量 JAVA_TOOL_OPTIONS 可以用来指定这个属性,但通常是这样完成的:

As Edward Grech points out, in a special case like this, the environment variable JAVA_TOOL_OPTIONS can be used to specify this property, but it's normally done like this:

java -Dfile.encoding=UTF-8 … com.x.Main

Charset.defaultCharset() 将反映对 file.encoding 属性的更改,但核心 Java 库中的大部分代码需要确定默认字符编码不要使用这种机制.

Charset.defaultCharset() will reflect changes to the file.encoding property, but most of the code in the core Java libraries that need to determine the default character encoding do not use this mechanism.

在编码或解码时,可以查询file.encoding属性或Charset.defaultCharset(),找到当前的默认编码,并使用合适的方法或构造函数重载来指定它.

When you are encoding or decoding, you can query the file.encoding property or Charset.defaultCharset() to find the current default encoding, and use the appropriate method or constructor overload to specify it.

这篇关于设置默认的 Java 字符编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆