简单了解字符编码【JAVA基础】

图片来自https://blog.csdn.net/qq_34745204/article/details/83786775

编码和解码

编码:字符串变成字节数组。
String–>byte[]; str.getBytes(charsetName);

解码:字节数组变成字符串。
byte[]–>String; new String(byte[],charsetName);

栗子

import java.io.IOException;
import java.util.Arrays;

public class EncodeDemo {

	public static void main(String[] args) throws IOException 
	{
		String s="你好";
		byte[] b1=s.getBytes("GBK");//编译		
		System.out.println(Arrays.toString(b1));//输出编译结果
		
		String s1=new String(b1,"ISO8859-1");//解码,查表错误
		System.out.println("s1="+s1);
         
		//对s1进行ISO8859-1编码
		byte[] b2=s1.getBytes("ISO8859-1");
		System.out.println(Arrays.toString(b2));//输出编译结果
		
		String s2=new String(b2,"gbk");//解码 查表
		System.out.println(s2);
	}

}

转换流中的字符编码

转换流的构造函数(流,编码格式)
InputStreamReader(new FileInputStream(“utf-8.txt”),“UTF-8”);
OutputStreamWriter(new FileInputStream(“utf-8.txt”),“UTF-8”);
转换流的编码应用
1,可以将字符以指定编码格式存储
2,可以对文本数据指定编码格式来解读
3,指定编码表的动作由构造函数完成

栗子

import java.io.*;
public class EncodeStream {

	public static void main(String[] args) throws IOException
	{
		writeText();
		raedText();

	}
	public static void raedText()throws IOException
	{
		InputStreamReader isr=new InputStreamReader(new FileInputStream("utf-8.txt"),"UTF-8");
		char[] buf=new char[10];
		int len=isr.read(buf);
		
		String str=new String(buf,0,len);
		System.out.println(str);
		
		isr.close();
	}
	public static void writeText()throws IOException
	{
		OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("utf-8.txt"),"UTF-8");
		osw.write("你好");
		osw.close();
	}

}

原创文章 27 获赞 2 访问量 1126

猜你喜欢

转载自blog.csdn.net/liudachu/article/details/105757877
今日推荐