更改 String(byte[]) 的默认编码 [英] Changing the default encoding for String(byte[])

查看:12
本文介绍了更改 String(byte[]) 的默认编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法改变 String(byte[]) 构造函数使用的编码?

Is there a way to change the encoding used by the String(byte[]) constructor ?

在我自己的代码中,我使用 String(byte[],String) 来指定编码,但我使用的是无法更改的外部库.

In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.

String src = "with accents: é à";
byte[] bytes = src.getBytes("UTF-8");
System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8"));
System.out.println("Default decoded: "+new String(bytes));

这个输出是:

UTF-8 decoded: with accents: é à
Default decoded: with accents: é à

我尝试更改系统属性 file.encoding 但它不起作用.

I have tried changing the system property file.encoding but it does not work.

推荐答案

在启动JVM之前需要更改locale;见:

You need to change the locale before launching the JVM; see:

Java,错误 ID 4163515

有些地方似乎暗示你可以通过在启动JVM时设置file.encoding变量来做到这一点,比如

Some places seem to imply you can do this by setting the file.encoding variable when launching the JVM, such as

java -Dfile.encoding=UTF-8 ...

...但我自己还没有尝试过.最安全的方法是在操作系统中设置一个环境变量.

...but I haven't tried this myself. The safest way is to set an environment variable in the operating system.

这篇关于更改 String(byte[]) 的默认编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆