编码解析

/*
 * InputStreamReader 
 * OutputStreamWriter
 * GBK: 两个字节组成,每个字节最高位都为1
 * UTF-8:三个字节著称,每个字节最高位都为1

 * 

part_01

public class EncodeStream {


	public static void main(String[] args) throws Exception {
		
		write();
		read();
		
	}
	public static void write() throws Exception
	{
		/*
		 * 1.将字节流FileOutputStream创建的文件EncodeStream.txt创换成字符流
		 * 2.将字符“你好”通过流对象osw写入文件
		 * 3.关闭流
		 * */
		//从内存输出到文件
		OutputStreamWriter osw = 
                new OutputStreamWriter(new FileOutputStream("EncodeStream.txt"),"utf-8");
		osw.write("你好");
		osw.close();
	}
	public static void read() throws Exception, FileNotFoundException
	{
		/*
		 * 1.将字节流文件EncodeStream.txt 按utf-8编码解析成字符传送到内存中
		 * */
		//从文件输入到内存
		InputStreamReader isr = 
                new InputStreamReader(new FileInputStream("EncodeStream.txt"),"utf-8");
		char[] buf = new char[10];
		int len = isr.read(buf);
		String str = new String(buf,0,len);
		System.out.println(str);		
	}


}

part_02

/*
 * 编码:字符串-->字节数组
 *
 * 解码:字节数组-->字符串
 * */
public class EncodeDemo {

	public static void main(String[] args) throws Exception {
		
		//编码
		String str = "你好";
		byte[] buf = str.getBytes("gbk");
		System.out.println(Arrays.toString(buf));
		//解码
		String str2 = new String(buf,"gbk");

		System.out.println(str2);
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值