字節流讀寫


存儲文件

 * IO流:永久存儲(耗時)
 * 數據庫:永久存儲
 * 
 * 基本的字節流
 * 文件字節輸入流/文件字節輸出流
 * 高效的字節流(緩沖流)
 * 
 * 操作一個視頻文件,來測試速度問題
 * 基本的字節流一次讀取一個字節 ://耗時:85772毫秒
 * 基本的字節流一次讀取一個字節數組 :共耗時:216毫秒
 * 
 * 高效的字節流一次讀取一個字節      :共耗時:682毫秒
 * 高效的字節流一次讀取一個字節數組:共耗時:49毫秒
 * 
 * @author Administrator
 *
 *
 *StringBuffer:提供了一個字符串緩沖區 (可以在緩沖區中不斷追加字符串)
 */
public class Test {

public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis() ;

// method1("e:\\abc.mp4","copy1.mp4") ;
// method2("e:\\abc.mp4","copy2.mp4") ;
// method3("e:\\abc.mp4","copy3.mp4") ;
method4("e:\\abc.mp4","copy4.mp4") ;

long end = System.currentTimeMillis() ;

System.out.println("共耗時:"+(end-start)+"毫秒");
}

// method1基本的字節流一次讀取一個字節
private static void method1(String src, String dest) throws Exception {
//封裝源文件和目標文件
FileInputStream fis = new FileInputStream(src) ;
FileOutputStream fos = new FileOutputStream(dest) ;

//讀寫操作
int by = 0 ;
while((by=fis.read())!=-1) {
//寫
fos.write(by);
}

//釋放資源
fis.close();
fos.close();

}

// method2基本的字節流一次讀取一個字節數組
private static void method2(String src, String dest) throws Exception {
//封裝文件
FileInputStream fis = new FileInputStream(src) ;
FileOutputStream fos = new FileOutputStream(dest) ;

//讀寫操作
byte[] bys = new byte[1024] ;//相當於一個緩沖區
int len = 0 ;
while((len=fis.read(bys))!=-1) {
fos.write(bys, 0, len);
}

//釋放資源
fis.close();
fos.close();

}


//method3高效的字節流一次讀取一個字節
private static void method3(String src, String dest) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src))  ;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)) ;

//一次讀個字節
int by = 0 ;
while((by=bis.read())!=-1) {
bos.write(by);
}
//釋放資源
bis.close();
bos.close();

}

//method4高效的流一次讀取一個字節數組
private static void method4(String src, String dest) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src))  ;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)) ;

//一次讀取一個字節數組
byte[] bys = new byte[1024] ; 
int len = 0 ;
while((len=bis.read(bys))!=-1) {
bos.write(bys, 0, len);
}

bis.close();
bos.close();

}}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM