一、概述
如何以编程方式正确设置JVM(1.5.x)使用的默认字符编码?
我读过,这-Dfile.encoding=whatever
曾经是使用旧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());
二、详解
file.encoding
必须在JVM启动时指定该属性。当你在运行main方法时,String.getBytes()
编码中使用的字符已经由InputStreamReader
和OutputStreamWriter
默认的构造函数永久缓存。
正如Edward Grech所指出的那样,在这种特殊情况下,JAVA_TOOL_OPTIONS
可以使用环境变量来指定此属性,但通常是这样完成的:
java -Dfile.encoding=UTF-8 … com.x.Main
Charset.defaultCharset()
将通过反射对file.encoding
属性进行更改,但是核心Java库中需要确定默认字符编码的大多数代码都不使用此机制。
编码或解码时,可以查询file.encoding
属性或Charset.defaultCharset()
查找当前的默认编码,并使用适当的方法或构造函数重载来指定它。
如若转载,请注明出处:https://www.javaidea.cn/article/8254.html