您的位置:首页 > 编程语言 > Java开发

Java字节缓冲流原理与用法详解

2020-04-02 12:08 921 查看

本文实例讲述了Java字节缓冲流原理与用法。分享给大家供大家参考,具体如下:

一 介绍

BufferInputStresm和BufferOutputStream
这两个流类为IO提供了带缓冲区的操作,一般打开文件进行写入或读取操作时,都会加上缓冲,这种流模式提高了IO的性能。

二 各类中方法比较

从应用程序中把输入放入文件,相当于将一缸水倒入另外一个缸中:
FileOutputStream的write方法:相当于一滴一滴地把水“转移过去。
DataOutputStream的writeXXX方法:相当于一瓢一瓢地把水转移过去。
BufferOutputStream的write方法:相当于一瓢一瓢先把水放入的桶中,再将桶中的水倒入缸中,性能提高了。

三 应用――带缓冲区的拷贝

/**
* 进行文件的拷贝,利用带缓冲的字节流
* @param srcFile
* @param destFile
* @throws IOException
*/
public static void copyFileByBuffer(File srcFile,File destFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件");
}
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destFile));
int c ;
while((c = bis.read())!=-1){
bos.write(c);
bos.flush();//刷新缓冲区
}
bis.close();
bos.close();
}

四 应用――单字节,不带缓冲的拷贝

/**
* 单字节,不带缓冲进行文件拷贝
* @param srcFile
* @param destFile
* @throws IOException
*/
public static void copyFileByByte(File srcFile,File destFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件");
}
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(destFile);
int c ;
while((c = in.read())!=-1){
out.write(c);
out.flush();
}
in.close();
out.close();
}

五 测试――各种拷贝比较

package com.imooc.io;
import java.io.File;
import java.io.IOException;
public class IOUtilTest4 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
long start = System.currentTimeMillis();
IOUtil.copyFileByByte(new File("e:\\javaio\\demo.mp3"), new File(
"e:\\javaio\\demo2.mp3")); //两万多毫秒
long end = System.currentTimeMillis();
System.out.println(end - start );
start = System.currentTimeMillis();
IOUtil.copyFileByBuffer(new File("e:\\javaio\\demo.mp3"), new File(
"e:\\javaio\\demo3.mp3"));//一万多毫秒
end = System.currentTimeMillis();
System.out.println(end - start );
start = System.currentTimeMillis();
IOUtil.copyFile(new File("e:\\javaio\\demo.mp3"), new File(
"e:\\javaio\\demo4.mp3"));//7毫秒
end = System.currentTimeMillis();
System.out.println(end - start );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

六 测试结果

13091
9067
10

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 字节缓冲流