字符编码

1、基本内容

存储:在计算机中存储字符都是存储字符所对应的二进制数值来表示的

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

最常用的字符编码:

1)GBK:对GB2312(简体中文编码)的增强

2)UTF-8:支持多种国家的语言,针对不同的字符的范围给出不同的字节表示,字母1个字节,中文3个字节。

2、范例:使用GBK的编码方式来写入和读取文件

package com.ri.byt.charset;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * 使用GBK的编码方式来写入文件和读取编码,编码必须一致,否则会出现乱码
 * @author Administrator
 *
 */
public class CharsetDemo {

	public static void main(String[] args) {
		
		//PrintCharset();
		ReadCharset();
	}
	
	public static void PrintCharset(){
		OutputStreamWriter ow = null;
		try {
			ow = new OutputStreamWriter(new FileOutputStream("66.txt"),"GBK");
			ow.write("中国");
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch ( IOException e) {
			e.printStackTrace();
		}finally{
			if(ow != null){
				try {
					ow.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	public static void ReadCharset(){
		InputStreamReader ow = null;
		try {
			ow = new InputStreamReader(new FileInputStream("66.txt"),"GBK");
			char[] chs = new char[1024];
			int len = ow.read(chs);
			System.out.println(new String(chs,0,len));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch ( IOException e) {
			e.printStackTrace();
		}finally{
			if(ow != null){
				try {
					ow.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

3、字符串的编码问题

写入的编码和读取的编码必须一致,否则会导致乱码。

package com.ri.byt.charset;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * 用什么编码就用什么来写,编码必须一致,全栈统一编码
 * @author Administrator
 *
 */
public class CharsetDemo1 {

	public static void main(String[] args) throws UnsupportedEncodingException {
	
		String str = "中国";
		//使用默认编码来编码(GBK)
		byte[] bsGbk = str.getBytes();
		//使用UTF-8来编码
		byte[] bsUtf = str.getBytes("UTF-8");
		//打印编码值
		PrintByte(bsGbk);
		//打印编码值所对应字符(gbk)
		System.out.println(new String(bsGbk));
		//打印UTF-8编码制
		PrintByte(bsUtf);
		//打印用UTF-8编码后的编码值对应的字符串,对应的构造器不一样
		System.out.println(new String(bsUtf,"UTF-8"));
	}
	
	public static void PrintByte(byte[] bs){
		for(byte b:bs){
			System.out.print(b+"  ");
		}
		
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值