一、缓冲流
读取大文件时,文件输入流输出流读取速度慢,Java中提供了一套缓冲流,提高IO流的效果 ****从 字节\字符 输入\输出流 读取文本,缓存字符、数组和行的高效读取 字节缓冲流和字符缓冲流 作用:提高效率 1.1字节缓冲流 字节输入缓冲流:BufferedInputStream 字节输出缓冲流:BufferedOutputStream (1) 字节输出缓冲流:BufferedOutputStream 例: //创建字节输出缓冲流对象 //继承自outputStream //构造方法new BufferedOutputStream(new FileOutputStream()) public static void main(String[] args)throws IOException{ BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("d:\\buffer.txt")); bos.write(65); //bos.write("hello".getBytes); byte[] b="hello world".get.Bytes(); bos.write(b); bos.write(b,1,3); bos.close(); } (2) 字节输入缓冲流 BufferedOutputStream 例: public static void main(String[] args)throws IOException{ //创建字节输入流的对象 BufferedInputStream bis=new BufferedInputStream(new FileInputStream("d:\\buffer.txt")); byte[] b=new byte[1024]; int len=0; while((len=bis.read(b))!=-1){ System.out.println(new String(b,0,len)); } } 1.2字符缓冲流 字符输入缓冲流:BufferedReader 字符输出缓冲流:BufferedWriter (1)字符输出缓冲流:BufferedWriter 特有方法:newLine()换行 字符缓冲流使用 例: public static void main(String[] args) throws IOException{ BufferedWriter bw=new BufferedWriter(new FileWriter("d:\\buffer1.txt")); bw.write(87); bw.newLine(); bw.write("你好");l bw.flush(); bw.close(); } (2)字符输入缓冲流:BufferedReader 特有方法:readLine() 读一行文字 结果:包含行的内容的字符串,不包含任何行终止字符,如果达到流的末尾,返回null 例: public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new FileReader("d:\\buffer1.txt")); String len=null; while((len=br.readLine())!=null){ System.out.println(len); } br.close(); } 1.3 用字节缓冲流进行文件的复制 public static void main(String[] args) throws Exception{ BufferedInputStream bis=new BufferedInputStream(new FileInputStream("d:\\timg.jpg")); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("c:\\timg.jpg")); byte[] b=new byte[1024*10]; int len=0; while((len=bis.read(b))!=-1){ bos.write(b,0,len); } bos.close(); bis.close(); }