zoukankan      html  css  js  c++  java
  • Java 字符集编码

    一、字符编码实例
    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系统

  • 相关阅读:
    HDU 4825 Xor Sum
    Linux下使用Crontab定时执行脚本
    HDU 4824 Disk Schedule
    Educational Codeforces Round 26 D. Round Subset 动态规划
    POJ 1833 排列
    HDU 1716 全排列
    HDU 1027 全排列
    Educational Codeforces Round 26 A C 之Python
    ACM输入输出之python
    标准C程序设计七---102
  • 原文地址:https://www.cnblogs.com/linlf03/p/11369291.html
Copyright © 2011-2022 走看看