学习内容:
1.字符流:
字符流用来读取或写入文本。
(1)输入流:
public class Test { public static void main(String[] args) { File f = new File("d:\test\test.txt"); try (FileReader fr =new FileReader(f);){ //char使用的是unicode,一个字符两个字节 char[] read = new char[(int)f.length()]; //注意txt文档内含有汉字,则length会大于实际字符个数,因为汉字占2个字符,导致输出时有方块 //如果是纯汉字文档,可以直接length/2,如果中英混合: //解决方案是加判断 if c!=0 int a= fr.read(read); for(char c:read) { if(c!=0) { System.out.println(c); } } char[] small = new char[1]; fr.read(small); int s = 0; while((s=fr.read(small))!=-1) { System.out.println(new String(small,0,s)); } } catch (IOException e) { e.printStackTrace(); } } }
(2)输出流
注意:字符输出流实际是向缓存区输出字符,当使用flush方法,或者流关闭时自动调用flush方法才会真正的将文字内容输出。
PS 如果write的是数字,则默认是输出ASCII码,想要输出真正的数字,要转为字符串进行输出!
public class Test { public static void main(String[] args) { File f = new File("d:\test\test.txt"); try (FileWriter fw = new FileWriter(f,true)){//与FileOutputStream类似,加true不覆盖 //FileWriter 实际写入的是缓存区,flush后才真正的写出到文件 //FileWriter流关闭时自动flush String str = "单个字符输出"; char[] write = str.toCharArray(); fw.write(write); fw.write("属性");//可直接写入字符串 fw.write("技能"); fw.flush(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter fw = new FileWriter(f,true); fw.write("测试"); //流没有关闭,也没有flush,则不会写出到文件 } catch (Exception e) { // TODO: handle exception } } }
(3)UTF-8字符集(非默认GBK字符集)文件的读写
利用InputStreamReader和OutputStreamWriter读写,注意,这两个流是分别建立在一个字节流的基础上的
public class Test4 { public static void main(String[] args) { File u = new File("d:\test\UTF8.txt"); File c = new File("d:\copy.txt"); //UTF-8字符集文件的读写 try ( FileInputStream fis = new FileInputStream(u); //将字节流转换为字符流,用finally关闭时只关reader、writer流即可 InputStreamReader fr = new InputStreamReader(fis,"utf-8");//自定义字符集 FileOutputStream fos = new FileOutputStream(c); OutputStreamWriter ow = new OutputStreamWriter(fos,"utf-8");//自定义字符集,默认GBK ) { char[] source = new char[(int)u.length()]; fr.read(source); ow.write(source); } catch (IOException e) { e.printStackTrace(); } } }
2.缓存流
当缓存写满后在执行读取、输出操作,减少硬盘IO,读写大文件时速度更快,缓存流必须建立在一个已存在的输入、输出流上
public class Test { //缓存流 public static void main(String[] args) { File f = new File("d:/test/LOL.txt"); try (FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); ){ while(true) { //逐行读取 String line = br.readLine(); if(line == null) { break; } System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } try(FileWriter fw = new FileWriter(f2); BufferedWriter bw = new BufferedWriter(fw);) { bw.write("buffered"); bw.write("writer"); } catch (Exception e) { e.printStackTrace(); } } }
PS available()返回整数,如果等于0,则表明该流内没有数据!