装饰流
IO流按功能可分为节点流和处理流(装饰流),装饰流是在节点流基础上进行操作可以提高IO流的性能。
如果不需要装饰流则需要对硬盘重复操作,性能不高,BufferedInputStream可以相当于设置一个缓冲区先将要读取的内容放在一辆车上统一进行存取(默认内容为8k)
(FilterInputStream为装饰流)
代码举例
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();
}
}
}
}
}
来源:CSDN
作者:weixin_42701161
链接:https://blog.csdn.net/weixin_42701161/article/details/104027868