work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java 字符集编码

Posted on 2019-08-17 16:54  work hard work smart  阅读(233)  评论(0编辑  收藏  举报
一、字符编码实例
1、NioTest13_In.txt文件内容拷贝到NioTest13_Out.txt文件中
public class NioTest13 {

    public static void main(String[] args) throws  Exception {
        String inputFile = "NioTest13_In.txt";
        String outFile = "NioTest13_Out.txt";

        RandomAccessFile inputRandomAccessFile = new RandomAccessFile(inputFile,"r");

        RandomAccessFile outputRandomAccessFile = new RandomAccessFile(outFile,"rw");

        long inputLength = new File(inputFile).length();

        FileChannel inputFileChannel = inputRandomAccessFile.getChannel();
        FileChannel outputFileChannel = outputRandomAccessFile.getChannel();

        MappedByteBuffer inputData = inputFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);
        System.out.println("================================");
        /*Charset.availableCharsets().forEach( (k,v) -> {
            System.out.println(k + ", " + v);
        });*/
        System.out.println("================================");

        Charset charset = Charset.forName("iso-8859-1"); //utf-8
        CharsetDecoder decoder = charset.newDecoder(); //字节数组转字符串
        CharsetEncoder encoder = charset.newEncoder(); //字符串转字符数组

        CharBuffer charBuffer = decoder.decode(inputData);

         ByteBuffer outputData = encoder.encode(charBuffer);

        outputFileChannel.write(outputData);

        inputRandomAccessFile.close();
        outputRandomAccessFile.close();
    }
}

  

2、创建"NioTest13_In.txt文件

 

3、执行后生成了NioTest13_Out.txt 文件

可以知道使用: Charset charset = Charset.forName("iso-8859-1"); //utf-8

使用iso-8859-1和utf-8,中文显示都是正常的

 

二、字符编码介绍

1、ASCII
7 bit表示一个字符,共计可以表示128种字符


2、ISO-8859-1(兼容ASCII)
8 bit表示一个字符,共计可以表示256种字符


3、gb2312
两个字节表示一个汉字

gbk(是gb2312的超集)
包括生僻的汉字

4、gb18030 最完整的汉字表示形式

5、big5 繁体中文

6、unicode, 所有国家的字符。采用了两个字节表示一个字符
缺点: 不适合英文国家的存储

7、UTF Unicode Transaction Format
unicode是一种编码方式,而UTF则是一种存储方式: UTF-8是unicode的实现方式之一
  1) UTF-16LE(little endian) UTF-16-BE(big endian)
  Zero Widht No-Break Space, 文件开头以0xFEFF(BE)开始, 以0xFFFE(LE)开始

 2) UTF-8,变长字符表示形式(英文ASCII,中文:一般来说,UTF-8会通过3个字节表示一个中文)

 3) BOM(Byte Order Mark),带有BOM头 文件开头以0xFEFF(BE)开始, 以0xFFFE(LE)开始,一般出现在Window系统