如何正确地设置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());

当前回答

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

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

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

其他回答

mvn clean install -Dfile.encoding=UTF-8 -Dmaven.repo.local=/path-to-m2

命令与exec-maven-plugin一起解决配置Jenkins任务时的以下错误。

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
Error occurred during initialization of VM
java.nio.charset.IllegalCharsetNameException: "UTF-8"
    at java.nio.charset.Charset.checkName(Charset.java:315)
    at java.nio.charset.Charset.lookup2(Charset.java:484)
    at java.nio.charset.Charset.lookup(Charset.java:464)
    at java.nio.charset.Charset.defaultCharset(Charset.java:609)
    at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:56)
    at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:111)
    at java.io.PrintStream.<init>(PrintStream.java:104)
    at java.io.PrintStream.<init>(PrintStream.java:151)
    at java.lang.System.newPrintStream(System.java:1148)
    at java.lang.System.initializeSystemClass(System.java:1192)

我们把这两个系统属性放在一起,它让系统把所有东西都变成utf8

file.encoding=UTF8
client.encoding.override=UTF-8

我的团队在装有Windows的机器上遇到了同样的问题。然后用两种方法解决了这个问题:

a)设置环境变量(即使在Windows系统首选项中)

JAVA_TOOL_OPTIONS -Dfile.encoding = UTF8

b)在pom.xml中引入以下片段:

 -Dfile.encoding=UTF-8 

 <jvmArguments>
 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001
 -Dfile.encoding=UTF-8
 </jvmArguments>

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

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

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

不清楚在这一点上你能做什么,不能控制什么。如果可以在目标文件上插入不同的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

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