我在 Windows 10 中运行我的 java 程序(默认字符集:Big5)。然后我从 args[0] 中得到了垃圾字符串。
我发现使用任何类型的字符集都很难将损坏的字符串(args[0])转换为可读字符串。
IDE(UTF-8)-->JVM(UTF-8损坏的字符串)-->main(UTF-8损坏的字符串)
UTF-8-->Big5 设定-->?定</p>
我认为当参数传递给 JVM 时,该参数已经损坏。
eclipse 运行配置中的参数
设定
eclipse运行配置中的VM参数
-Dfile.encoding=UTF-8
eclipse中常见的运行配置编码:UTF-8
java 源文件(CharsetARGTest.java) 编码字符集:UTF-8
CharsetARGTest.java
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
public class CharsetARGTest {
public static void main(String[] args) throws UnsupportedEncodingException {
// arg:
// IDE(UTF-8)-->???(Big5)-->JVM(damaged string)-->main(damaged string)
System.out.println("default charset:"+Charset.defaultCharset());
String str="设定";
System.out.println("String(UTF-8):"+str);
System.out.println("UTF-8 bytes:");
dump_bytes(str.getBytes("UTF-8"));
System.out.println("GBK bytes to String(GBK-->GBK):"+new String(str.getBytes("GBK"),"GBK"));
System.out.println("GBK bytes:");
dump_bytes(str.getBytes("GBK"));
System.out.println("UTF-8 bytes to String(UTF-8-->UTF-8):"+new String(str.getBytes(),"UTF-8"));
System.out.println("UTF-8 bytes:");
dump_bytes(str.getBytes());
System.out.println("Big5 bytes to String(Big5-->Big5):"+new String(str.getBytes("Big5"),"Big5"));
System.out.println("Big5 bytes:");
dump_bytes(str.getBytes("Big5"));
System.out.println("\n");
System.out.println("arg:"+args[0]);
System.out.println("Big5 bytes:");
dump_bytes(args[0].getBytes("Big5"));
System.out.println("UTF-8 bytes:");
dump_bytes(args[0].getBytes("UTF-8"));
}
static void dump_bytes(byte[] a) throws UnsupportedEncodingException {
for(byte c:a) {
System.out.print(c+" ");
}
System.out.print("\n");
}
static boolean bytesCompare(byte[] a, byte[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
}
输出
default charset:UTF-8
String(UTF-8):设定
UTF-8 bytes:
-24 -82 -66 -27 -82 -102
GBK bytes to String(GBK-->GBK):设定
GBK bytes:
-55 -24 -74 -88
UTF-8 bytes to String(UTF-8-->UTF-8):设定
UTF-8 bytes:
-24 -82 -66 -27 -82 -102
Big5 bytes to String(Big5-->Big5):?定
Big5 bytes:
63 -87 119
arg:?定
Big5 bytes:
63 -87 119
UTF-8 bytes:
63 -27 -82 -102