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

当前回答

试试这个:

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

其他回答

我们有同样的问题。我们系统地尝试了本文(和其他文章)中的一些建议,但都无济于事。我们还尝试了添加-Dfile。encoding=UTF8和似乎没有工作。

对于遇到此问题的人,下面的文章最终帮助我们了解了区域设置如何破坏Java/Tomcat中的unicode/UTF-8

http://www.jvmhost.com/articles/locale-breaks-unicode-utf-8-java-tomcat

在~/. conf中正确设置区域设置。Bashrc文件为我们工作。

我的团队在装有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>

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

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

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

我不能回答你最初的问题,但我想给你一些建议——不要依赖JVM的默认编码。最好显式地指定所需的编码(例如:"UTF-8")。这样,您就知道它即使跨不同的系统和JVM配置也能工作。

试试这个:

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