Eclipse中修改getBytes()的默认编码格式


Eclipse中编写程序,String.getBytes()函数的默认编码格式一般是IDE中工程的Properties设定值。

要在运行时进行修改getBytes()的默认编码格式,一般使用-Dfile.encoding的运行参数。

代码样例如下所示:

  1. void Test02() {  
  2.       D(System.getProperty("file.encoding"));  
  3.     try {  
  4.       String str = "测试";  
  5.         
  6.       byte[] bytes = str.getBytes();  
  7.       printBytes(bytes);  
  8.   
  9.       bytes = str.getBytes("utf-8");  
  10.       printBytes(bytes);  
  11.       bytes = str.getBytes("gbk");  
  12.       printBytes(bytes);  
  13.       bytes = str.getBytes("gb18030");  
  14.       printBytes(bytes);  
  15.   
  16.       System.setProperty("file.encoding""GBK");  
  17.       D("/n"+System.getProperty("file.encoding"));  
  18.   
  19.       bytes = str.getBytes();  
  20.       printBytes(bytes);  
  21.   
  22.       bytes = str.getBytes("utf-8");  
  23.       printBytes(bytes);  
  24.       bytes = str.getBytes("gbk");  
  25.       printBytes(bytes);  
  26.       bytes = str.getBytes("gb18030");  
  27.       printBytes(bytes);  
  28.         
  29.         
  30.     } catch (UnsupportedEncodingException e) {  
  31.       e.printStackTrace();  
  32.     }  
  33. }  
  34.   
  35. void printBytes(byte[] bytes) {  
  36.       int i=0;  
  37.       for (byte b : bytes) {  
  38.         if (i++%10 == 0) D("");  
  39.         System.out.print("/t" + (0x00ff & b));  
  40.       }  
  41. }  

相关内容