java 字节缓冲_Java字节缓冲流原理与用法详解
本文實例講述了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 字节缓冲_Java字节缓冲流原理与用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 杀存储过程进程_SQL SE
- 下一篇: python opencv resize