Java系列(50)——字符集编码

本系列博客汇总在这里:Java系列_汇总

目录

  • 一、字符集编码概述
  • 二、使用给定编码方式来写入和读取文件
    • 1、写入
    • 2、读取
  • 三、字符串编码解析


一、字符集编码概述

  1. 存储
    在计算机中存储字符都是存储的字符所对应的数值,以二进制的形式表示。

  2. 展示
    去相关的编码表中去查找该值(存储的值)所对应的字符。

  3. 常见的
    (1)ASCII表:用7bit来表示存储数据。
    Java系列(50)——字符集编码_第1张图片(2)ISO-8859-1(拉丁码表):用 8bit 来表示。
    (3)GB2312:简体中文编码(国标码)。
    (4)GBK:对 GB2312 做了增强。
    (5)GB18030:对 GBK 做了增强。
    (6)BIG5:支持繁体。
    (7)Unicode:支持多种国家的语言,这是国际标准,用 2 个字节来存储。缺点在于不管是什么字符都用 2 个字节,会有浪费。
    (8) UTF-8:支持多种国家的语言,针对不同的字符的范围给出不同的字节表示。

    • 0,a,A用一个字符存储。
    • 中间的范围用二个字节。
    • 中文就使用 3 个字节。
    • 写入的编码和读取的编码必须要一致,否则会有乱码。

二、使用给定编码方式来写入和读取文件

Java系列(50)——字符集编码_第2张图片
Java系列(50)——字符集编码_第3张图片

1、写入

  • 示例
    public static void main(String[] args)
    {
    	PrintWriter pw = null;
    	try
    	{
    		// 默认编码就是 GBK
    		// 把“魏宇轩”转换成字节然后按照 UTF-8 的编码方式存储到文件中
    		pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("f.txt"), "UTF-8"), true);
    		pw.println("魏宇轩");
    
    	} catch (UnsupportedEncodingException e)
    	{
    		e.printStackTrace();
    	} catch (FileNotFoundException e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if (pw != null)
    			pw.close();
    	}
    }
    
    在这里插入图片描述

2、读取

  • 示例
    public static void main(String[] args)
    {
    	BufferedReader br = null;
    	try
    	{
    		br = new BufferedReader(new InputStreamReader(new FileInputStream("f.txt"), "UTF-8"));
    		char[] chs = new char[1024];
    		int len = br.read(chs);
    		System.out.println( new String(chs,0,len));
    	} catch (Exception e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if (br != null)
    		{
    			try
    			{
    				br.close();
    			} catch (IOException e)
    			{
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    Java系列(50)——字符集编码_第4张图片
    注意:写入和读取的字符编码务必一致,否则会出现乱码!

三、字符串编码解析

  • 示例
    public static void main(String[] args) throws Exception
    {
    	String str = "魏宇轩";
    	
    	
    	// 使用GBK编码方式把字符串编码为字节
    	byte[] bs = str.getBytes();
    	
    	for (int i = 0; i < bs.length; i++)
    	{
    		System.out.print(bs[i] + "\t");
    	}
    	
    	System.out.println("\n------------------------------解码-------------------------------");	
    	// 使用 GBK 编码方式解码
    	String str1 = new String(bs, "GBK");
    	System.out.println("\n"+str1);
    	System.out.println("\n\n");
    	
    	
    	// 使用UTF-8编码方式把字符串编码为字节
    	byte[] bs1 = str.getBytes("UTF-8");
    	for (int i = 0; i < bs1.length; i++)
    	{
    		System.out.print(bs1[i] + "\t");
    	}
    	
    	System.out.println("\n-------------------------------解码-------------------------------");	
    	// 使用 UTF-8 编码方式解码
    	String str2 = new String(bs1, "UTF-8");
    	System.out.println("\n"+str2);
    }
    
    Java系列(50)——字符集编码_第5张图片

如有错误,欢迎指正!

你可能感兴趣的:(Java系列(更新完))