计算机只能存储字节数组,他也只能读取字节数组,
人为规定好,字节和字母的对应关系,这样看到一串字节,就可以知道想表达的是什么。
ASCII编码例子: I love you 73 32 108 111 118 101 32 121 111 117
人们为了表示自己国家的文字来交流,发明了各种各样的编码。
windows 在中国大陆编码ANSI默认就对应了GBK
字符流,就是指定好编码再读取或写入,将外部的字节流按照指定编码转化成java内部的编码存储。java内部编码是UTF-16.
package 指针23期java教学; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.CharBuffer; public class encode { public static void main(String[] args) { char[] array=new char[512]; try( //Reader in=new FileReader("test.txt"); 默认使用ANSI编码来读取。 //指定编码来读取。 Reader in= new InputStreamReader(new BufferedInputStream(new FileInputStream("test.txt")),"GBK"); //Writer out=new FileWriter("tttt"); 默认使用ANSI编码去写入。 //指定编码来写入。 Writer out=new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream("tttt.txt")),"utf-8"); ){ /* out.write("测试数据"); out.flush(); 字符流写入必须flush才能确保一定输出到目标。close时也会调用flush。 */ char buff[]=new char[512]; while(in.read(buff)!=-1){ System.out.println(buff); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }