文本文件常用编码

1.字符串存入文件中,需要将字符串转化为字节后才能存入 ,存入字节时,字符串需要通过特定的编码规则编码后存入(常用编码规则:GBK(中文平台默认),uft-8,uft-16be)

一个字符串放入文本文件---》可以认为是字符串的序列化

2.从文本中读取字符串也需要相同的编码方式
    从文本文件中读取字符串---》可以认为是字符串的反序列化

 1 import java.io.UnsupportedEncodingException;
 2 import java.util.Arrays;
 3 
 4 public class zh {
 5       public static void main(String[] args) {
 6         String aa="ABC我";
 7         //默认编码形式
 8         byte[] b=aa.getBytes();
 9         System.out.println(Arrays.toString(b));
10         for (byte c : b) {
11             System.out.print(Integer.toHexString(c&0xff)+" ");
12         }
13         String string=new String(b);
14         
15         System.out.println(string);
16         
17         //GBK编码形式
18         System.out.println("========================");
19         try {
20             byte[] v=aa.getBytes("GBK");
21             for (byte c : b) {
22                 System.out.print(Integer.toHexString(c&0xFF)+" ");
23                 
24             }
25             
26             String string1=new String(v,"GBK");
27             System.out.println(string);
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31         System.out.println(Arrays.toString(b));
32         
33         //utf-8编码形式
34         System.out.println("==========================");
35         try {
36             byte[] g=aa.getBytes("utf-8");
37             for (byte c : g) {
38                 System.out.print(Integer.toHexString(c&0xFF)+" ");
39                 
40             }
41             String string2=new String(g,"utf-8");
42             System.out.print(string2);
43         } catch (Exception e) {
44             // TODO: handle exception
45         }
46     }
47 }

输出结果:

[65, 66, 67, -50, -46]
41 42 43 ce d2 ABC我
========================
41 42 43 ce d2 ABC我
[65, 66, 67, -50, -46]
==========================
41 42 43 e6 88 91 ABC我

posted on 2016-06-08 11:36  lgshiwoo  阅读(739)  评论(0编辑  收藏  举报