更改String(byte [])的默认编码
时间:2020-03-05 18:58:21 来源:igfitidea点击:
有没有办法更改String(byte [])构造函数使用的编码?
在我自己的代码中,我使用String(byte [],String)指定编码,但是我使用的是无法更改的外部库。
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
,但是它不起作用。
解决方案
回答
引自defaultCharset()
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.
在大多数操作系统中,我们可以使用环境变量来设置字符集。
回答
我们需要在启动JVM之前更改语言环境。看:
Java,错误ID 4163515
有些地方似乎暗示我们可以通过在启动JVM时设置file.encoding变量来做到这一点,例如
java -Dfile.encoding=UTF-8 ...
...但是我自己还没有尝试过。最安全的方法是在操作系统中设置环境变量。