* 缓冲流 (高效流)
* 内部自带一个缓冲区(相当有自带一个字节数组)
* BufferedOutputStream(写文件) 缓冲字节输出流
* BufferedInputStream(读文件) 缓冲字节输入流
用缓冲流输出
FileOutputStream fos =new FileOutputStream("/Users/lanou/Desktop/Test/guifen.txt"); //构建一个缓冲流 BufferedOutputStream bos =new BufferedOutputStream(fos); //写 bos.write("guifen".getBytes()); bos.close();
用缓冲流输入
FileInputStream fis = new FileInputStream("/Users/lanou/Desktop/Test/guifen.txt"); BufferedInputStream bis = new BufferedInputStream(fis); int len = -1; byte[] bts = new byte[1024]; while ((len = bis.read(bts)) != -1) { System.out.print(new String(bts, 0, len)); } bis.close();
使用缓冲流看是否读取更快
public class Demo09 { public static void main(String[] args) { Temp temp = new InputStream(); temp.printTime(); Temp copy = new Copy(); copy.printTime(); } } abstract class Temp { public void printTime() { long time1 = System.currentTimeMillis(); input(); long time2 = System.currentTimeMillis(); long time = time2 - time1; System.out.println(time + "毫秒"); } public abstract void input(); } class Copy extends Temp { @Override public void input() { FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { fis = new FileInputStream("/Users/lanou/Desktop/Test/java核心技术 卷1 基础知识 原书第9版 完整中文版 .pdf"); fos = new FileOutputStream("/Users/lanou/Desktop/Test/王者荣耀核心技术 .pdf"); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); int len = -1; byte[] bts = new byte[1024]; while ((len = bis.read(bts)) != -1) { bos.write(bts, 0, len); } } catch (FileNotFoundException e) { throw new RuntimeException("找不到文件"); } catch (IOException e) { throw new RuntimeException("读取失败"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { throw new RuntimeException("流关闭失败"); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { throw new RuntimeException("流关闭失败"); } } } } } } } class InputStream extends Temp { //2355毫秒 @Override public void input() { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("/Users/lanou/Desktop/Test/java核心技术 卷1 基础知识 原书第9版 完整中文版 .pdf"); fos = new FileOutputStream("/Users/lanou/Desktop/Test/dnf核心技术 .pdf"); int len = -1; byte[] bts = new byte[1024]; while ((len = fis.read(bts)) != -1) { fos.write(bts, 0, len); } } catch (FileNotFoundException e) { throw new RuntimeException("找不到文件"); } catch (IOException e) { throw new RuntimeException("文件读取失败"); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { throw new RuntimeException("流关闭失败"); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { throw new RuntimeException("流关闭失败"); } } } } } } }