java 字节缓存流 字符缓存流
一、字节缓存流(速度更快)
1、BufferedInputStream 字节输入缓存流
a、构造
new BufferedInputStream(FileInputStream对象)
b、方法
与FileInputStream相似
2、BufferedOutputStream
a、构造
new BufferedOutputStream(FileOutputStream对象);
b、方法
与FileOutStream相似
3、案例
package com.wt.buffer; import java.io.*; public class Demon01 { public static void main(String[] args) { long start = System.currentTimeMillis(); try( // 字节缓存输入对象 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\data\\1.jpg")); // 字节缓存输出对象 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\data\\10.jpg")); ) { byte[] bytes = new byte[1024]; int len; while ((len=bis.read(bytes))!=-1){ bos.write(bytes, 0, len); } } catch (IOException e) { throw new RuntimeException(e); } long end = System.currentTimeMillis(); System.out.println(end-start); } }
二、字符缓存流
1、BufferedWriter 字符缓存输入流
a、构造
new BufferedWriter(FileWriter对象)
b、方法
方法与FileWriter相似
新方法:newLine(),新增一行
c、案例
package com.wt.buffer; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Demon02 { public static void main(String[] args) { try(BufferedWriter bw = new BufferedWriter(new FileWriter("module3\\4.txt"))){ bw.write("日照香炉生紫烟"); // 添加新的一行 bw.newLine(); bw.write("遥看瀑布挂前川"); bw.newLine(); bw.write("飞流直下三千尺"); bw.newLine(); bw.write("疑是银河落九天"); } catch (IOException e) { throw new RuntimeException(e); } } }
2、BufferedReader 字符缓存输出流
a、构造
new BufferedReader(FileReader对象)
b、方法
与FileReader相似
新方法:readLine(),按行读取,没有数据。返回值为null
c、案例
package com.wt.buffer; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Demon03 { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("module3\\4.txt"))){ String line = null; while ((line = br.readLine())!=null){ System.out.println(line); } } catch (IOException e) { throw new RuntimeException(e); } } }