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

我读过-Dfile。encoding=任何以前的jvm使用的方式。我没有那种奢侈,原因我就不多说了。

我试过:

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

并且属性被设置了,但是它似乎没有导致下面最后的getBytes调用使用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());

当前回答

我有一个非常有效的方法!!

System.setProperty("file.encoding","UTF-8");
Field charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null,null);

通过这种方式,您将欺骗JVM,它会认为字符集没有设置,并使它在运行时再次设置为UTF-8 !

其他回答

我正在使用Amazon (AWS) Elastic Beanstalk,并成功地将其更改为UTF-8。

在Elastic Beanstalk中,进入配置>软件,“环境属性”。 添加(name) JAVA_TOOL_OPTIONS和(value) -Dfile.encoding=UTF8

保存后,环境将以UTF-8编码重新启动。

试试这个:

    new OutputStreamWriter( new FileOutputStream("Your_file_fullpath" ),Charset.forName("UTF8"))

不清楚在这一点上你能做什么,不能控制什么。如果可以在目标文件上插入不同的OutputStream类,则可以使用OutputStream的子类型,它将字符串转换为您定义的字符集下的字节,默认情况下是UTF-8。如果修改的UTF-8足够满足你的需要,你可以使用DataOutputStream.writeUTF(String):

byte inbytes[] = new byte[1024];
FileInputStream fis = new FileInputStream("response.txt");
fis.read(inbytes);
String in = new String(inbytes, "UTF8");
DataOutputStream out = new DataOutputStream(new FileOutputStream("response-2.txt"));
out.writeUTF(in); // no getBytes() here

如果这种方法不可行,那么在这里阐明在数据流和执行环境方面哪些可以控制,哪些不能控制,可能会有所帮助(尽管我知道有时说起来容易做起来难)。祝你好运。

从JVM™工具接口文档…

由于不能总是访问或修改命令行,例如在嵌入式vm中或只是在脚本深处启动的vm中,因此提供了一个JAVA_TOOL_OPTIONS变量,以便在这些情况下可以启动代理。

通过将(Windows)环境变量JAVA_TOOL_OPTIONS设置为-Dfile。encoding=UTF8, (Java) System属性将在每次JVM启动时自动设置。您将知道参数已被拾取,因为下面的消息将被发布到System.err:

选择JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8

我有一个非常有效的方法!!

System.setProperty("file.encoding","UTF-8");
Field charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null,null);

通过这种方式,您将欺骗JVM,它会认为字符集没有设置,并使它在运行时再次设置为UTF-8 !