/*
* InputStreamReader
* OutputStreamWriter
* GBK: 两个字节组成,每个字节最高位都为1
* UTF-8:三个字节著称,每个字节最高位都为1
* 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);
}
}
576

被折叠的 条评论
为什么被折叠?



