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

当前回答

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

其他回答

最近,我偶然接触了一家本地公司的Notes 6.5系统,发现在非中文本地Windows安装系统上,web邮件会显示无法识别的字符。我在网上查了几周,几分钟前才发现:

在Java属性中,将以下字符串添加到Runtime Parameters

-Dfile.encoding=MS950 -Duser.language=zh -Duser.country=TW -Dsun.jnu.encoding=MS950

在这种情况下,UTF-8设置将不起作用。

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

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

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

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

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

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

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

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

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

如果您正在使用Spring Boot并希望传递参数文件。你必须像这样运行它:

mvn spring-boot:run -Drun.jvmArguments="-Dfile.encoding=UTF-8"

这是我们所需要的,因为我们使用JTwig模板和操作系统有ANSI_X3.4-1968,我们通过system .out.println(system . getproperty ("file.encoding"));

希望这能帮助到一些人!