当前位置: 代码迷 >> 综合 >> IO操作(3):装饰流(BufferedInput/OutputStream)
  详细解决方案

IO操作(3):装饰流(BufferedInput/OutputStream)

热度:84   发布时间:2024-01-25 17:35:34.0

装饰流

IO流按功能可分为节点流和处理流(装饰流),装饰流是在节点流基础上进行操作可以提高IO流的性能。
如果不需要装饰流则需要对硬盘重复操作,性能不高,BufferedInputStream可以相当于设置一个缓冲区先将要读取的内容放在一辆车上统一进行存取(默认内容为8k)

代码举例

BufferedInputStream

public class DecorateBufferInput {public static void main(String[] args) throws IOException {//1、创建源File src = new File("abc.txt");//2、选择流InputStream is = null;BufferedInputStream bis = null;try {is  = new FileInputStream(src);bis = new BufferedInputStream(is);            //设置缓冲数组默认为8K//上面的可以直接改写为下面一行//is = new BufferedInputStream(new FileInputStream(src));//3、操作分段读取byte[] flush = new byte[1024];int len = -1;while((len=is.read())!=-1){String str = new String(flush,0,len);System.out.println(str);}}catch(Exception e){e.printStackTrace();}finally {if(null!=is){is.close();}if(null!=bis){bis.close();}}}
}

BufferedOutputStream

public class DecorateBufferedOutput {public static void main(String[] args) {File dest = new File("dest.txt");OutputStream os = null;try {os = new BufferedOutputStream(new FileOutputStream(dest));String msg = "ilovewangjiyu";byte[] datas = msg.getBytes();os.write(datas,0,datas.length);os.flush();}catch(IOException e){e.printStackTrace();}finally {if(null!=os){try {os.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}}
}