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

当前回答

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

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

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

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

其他回答

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

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

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

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

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

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

在这种情况下,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"));

希望这能帮助到一些人!

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

试试这个:

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