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

查看:189
本文介绍了设置默认的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启动;在输入main方法时, String.getBytes()使用的字符编码以及 InputStreamReader

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.

由于 a / 623036/3474> 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天全站免登陆