詳解Java中IO字節(jié)流基本操作(復(fù)制文件)并測試性能
此次案例將以復(fù)制文件的形式來演示IO字節(jié)流的基本操作,復(fù)制一個mp3文件,文件信息如下圖:
main方法測試
public static void main(String[] args) throws Exception { //源文件 String srcFile = "src/a.mp3"; //目的文件 String destFile = "src/b.mp3"; long start = System.currentTimeMillis(); ... 復(fù)制文件方法 ... long end = System.currentTimeMillis(); System.out.println("共耗時"+(end-start)+"毫秒"); }
一、一次讀取一個字節(jié)
//一次讀取一個字節(jié) public static void copy1(String srcFile,String destFile) throws Exception { //封裝文件 InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); //復(fù)制文件 int b = 0; while ((b = in.read()) != -1) { out.write(b); } //釋放資源 in.close(); out.close(); }
運(yùn)行截圖:
二、一次讀取一個字節(jié)數(shù)組
// 一次讀取一個字節(jié)數(shù)組 public static void copy2(String srcFile, String destFile) throws Exception { // 封裝文件 InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); // 復(fù)制文件 byte[] buff = new byte[1024]; int len = 0; while ((len = in.read(buff)) != -1) { out.write(buff, 0, len); } // 釋放資源 in.close(); out.close(); }
運(yùn)行截圖:
三、使用高效緩沖區(qū)一次讀取一個字節(jié)
/ 使用高效緩沖區(qū)一次讀取一個字節(jié) public static void copy3(String srcFile, String destFile) throws Exception { // 封裝文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); // 復(fù)制文件 int b = 0; while ((b = bis.read()) != -1) { bos.write(b); } // 釋放資源 bis.close(); bos.close(); }
運(yùn)行截圖:
四、使用高效緩沖區(qū)一次讀取一個字節(jié)數(shù)組
// 使用高效緩沖區(qū)一次讀取一個字節(jié)數(shù)組 public static void copy4(String srcFile, String destFile) throws Exception { // 封裝文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); // 復(fù)制文件 byte[] buf = new byte[1024]; int len = 0; while ((len = bis.read(buf)) != -1) { bos.write(buf, 0, len); } // 釋放資源 bis.close(); bos.close(); }
運(yùn)行截圖:
注:每臺測試的速度結(jié)果不一樣
以上所述是小編給大家介紹的Java中IO字節(jié)流基本操作(復(fù)制文件)并測試性能,詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
關(guān)于Https協(xié)議和HttpClient的實現(xiàn)詳解
這篇文章主要給大家介紹了關(guān)于Https協(xié)議和HttpClient實現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05SpringBoot配置默認(rèn)HikariCP數(shù)據(jù)源
咱們開發(fā)項目的過程中用到很多的開源數(shù)據(jù)庫鏈接池,比如druid、c3p0、BoneCP等等,本文主要介紹了SpringBoot配置默認(rèn)HikariCP數(shù)據(jù)源,具有一定的參考價值,感興趣的可以了解一下2023-11-11Spring?Boot請求處理之常用參數(shù)注解使用教程
這篇文章主要給大家介紹了關(guān)于Spring?Boot請求處理之常用參數(shù)注解使用的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-03-03