java _io_字节缓冲流(装饰器)输入、输出

*装饰模式

  • 字节缓冲流
  • BufferedInputStream bis=new BufferedInputStream(inputStream is)
  • BufferedOutputStream bos=new BufferedOutputStream(OutputStream os)
  • 最底层一定是节点流
  • 只需要释放最外层的处理流,若要手动关闭遵循从里到外的顺序关闭(从字节流到处理流)
  • 默认为8k,可以改变
    //参数是字节输入流对象
    InputStream is =new BufferedInputStream(new InputStream(f));
    OutputStream os=new BufferedOutputStream(new OutputStream(f));

处理流装饰字节流输入:

    File f =new File("C:\\Users\\10853\\eclipse-workspace\\hell\\src\\hell\\abc");

    InputStream is =null;
    try {
        **is=new BufferedInputStream(new FileInputStream(f));**

        byte[] flush =new byte[1024];
        int len=-1;
        while((len=is.read(flush))!=-1)
        {
            is.read(flush,0,len);
        }
    }catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }catch(IOException e)
    {
        e.printStackTrace();
    }finally {

        try {

            if(null!=is)
            {
                i**s.close();**  //关闭处理流,会自动关闭字节流
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }

    }

处理流装饰字节流输出:

    File f=new File("D:d/c.txt");

    OutputStream os =null;
    try
    {
    **  os=new BufferedOutputStream(new FileOutputStream(f));**
        String s="addaa";
        byte[] datas=s.getBytes();
        os.write(datas,0,datas.length);
        os.flush();

    }catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }catch(IOException e)
    {
        e.printStackTrace();
    }finally {
        try {
            if(**null!=os**)  //关闭处理流会自动关闭字节流
            {
                os.close();
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }   
    }
上一篇:java _io_字符缓冲流的输入、输出


下一篇:Java并发编程:volatile关键字解析