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

查看:458
本文介绍了设置默认的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天全站免登陆