java中文件複製的4種方式

来源:https://www.cnblogs.com/xxjcai/archive/2019/09/24/11581987.html
-Advertisement-
Play Games

今天一個同事問我文件複製的問題,他一個100M的文件複製的指定目錄下竟然成了1G多,嚇我一跳,後來看了他的代碼發現是自己通過位元組流複製的,定義的位元組數組很大,導致複製後目標文件非常大,其實就是空行等一些無效空間。我也是很少用這種方式拷貝問價,大多數用Apache提供的commons-io中的File ...


      今天一個同事問我文件複製的問題,他一個100M的文件複製的指定目錄下竟然成了1G多,嚇我一跳,後來看了他的代碼發現是自己通過位元組流複製的,定義的位元組數組很大,導致複製後目標文件非常大,其實就是空行等一些無效空間。我也是很少用這種方式拷貝問價,大多數用Apache提供的commons-io中的FileUtils,後來在網上查了下,發現還有其他的方式,效率更高,所以在此整理一下,也是自己的一個學習。

1. 使用FileStreams複製

比較經典的一個代碼,使用FileInputStream讀取文件A的位元組,使用FileOutputStream寫入到文件B。

public static void copy(String source, String dest, int bufferSize) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(new File(source));
        out = new FileOutputStream(new File(dest));

        byte[] buffer = new byte[bufferSize];
        int len;

        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    } catch (Exception e) {
        Log.w(TAG + ":copy", "error occur while copy", e);
    } finally {
        safelyClose(TAG + ":copy", in);
        safelyClose(TAG + ":copy", out);
    }
}   
2.

2、使用FileChannel

Java NIO包括transferFrom方法,根據文檔應該比文件流複製的速度更快。

 

public static void copyNio(String source, String dest) {
    FileChannel input = null;
    FileChannel output = null;

    try {
        input = new FileInputStream(new File(from)).getChannel();
        output = new FileOutputStream(new File(to)).getChannel();
        output.transferFrom(input, 0, input.size());
    } catch (Exception e) {
        Log.w(TAG + "copyNio", "error occur while copy", e);
    } finally {
        safelyClose(TAG + "copyNio", input);
        safelyClose(TAG + "copyNio", output);
    }
}

3、 使用Apache Commons IO複製
Appache Commons IO 提供了一個FileUtils.copyFile(File from, File to)方法用於文件複製,如果項目里使用到了這個類庫,使用這個方法是個不錯的選擇。
它的內部也是使用Java NIO的FileChannel實現的。
commons-io的路徑:http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html。裡面還有很多實用的方法,如拷貝目錄、拷貝指定格式文件等。
private static void  copyFileByApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}
4、使用Java7的Files類複製
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}
我沒有親測,找了下網友的測試程式和輸出,性能數據供大家參考(來源:https://www.jb51.net/article/70412.htm)
import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.channels.FileChannel;

import java.nio.file.Files;

import org.apache.commons.io.FileUtils;

public class CopyFilesExample {
  public static void main(String[] args) throws InterruptedException,

      IOException {

    File source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile1.txt");

    File dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile1.txt");

  

    // copy file using FileStreams

    long start = System.nanoTime();

    long end;

    copyFileUsingFileStreams(source, dest);

    System.out.println("Time taken by FileStreams Copy = "

        + (System.nanoTime() - start));
 
    // copy files using java.nio.FileChannel

    source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile2.txt");

    dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile2.txt");

    start = System.nanoTime();

    copyFileUsingFileChannels(source, dest);

    end = System.nanoTime();

    System.out.println("Time taken by FileChannels Copy = " + (end - start));
    // copy file using Java 7 Files class

    source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile3.txt");

    dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile3.txt");

    start = System.nanoTime();

    copyFileUsingJava7Files(source, dest);

    end = System.nanoTime();

    System.out.println("Time taken by Java7 Files Copy = " + (end - start));

    // copy files using apache commons io

    source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile4.txt");

    dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile4.txt");

    start = System.nanoTime();

    copyFileUsingApacheCommonsIO(source, dest);

    end = System.nanoTime();

    System.out.println("Time taken by Apache Commons IO Copy = "

        + (end - start));
  }

  private static void copyFileUsingFileStreams(File source, File dest)

      throws IOException {

    InputStream input = null;

    OutputStream output = null;

    try {

      input = new FileInputStream(source);

      output = new FileOutputStream(dest);

      byte[] buf = new byte[1024];

      int bytesRead;

      while ((bytesRead = input.read(buf)) > 0) {

        output.write(buf, 0, bytesRead);

      }

    } finally {

      input.close();

      output.close();

    }

  }

  private static void copyFileUsingFileChannels(File source, File dest)

      throws IOException {

    FileChannel inputChannel = null;

    FileChannel outputChannel = null;

    try {

      inputChannel = new FileInputStream(source).getChannel();

      outputChannel = new FileOutputStream(dest).getChannel();

      outputChannel.transferFrom(inputChannel, 0, inputChannel.size());

    } finally {

      inputChannel.close();

      outputChannel.close();

    }

  }

  private static void copyFileUsingJava7Files(File source, File dest)

      throws IOException {

    Files.copy(source.toPath(), dest.toPath());

  }

  private static void copyFileUsingApacheCommonsIO(File source, File dest)

      throws IOException {

    FileUtils.copyFile(source, dest);

  }
}

輸出:

Time taken by FileStreams Copy = 127572360

Time taken by FileChannels Copy = 10449963

Time taken by Java7 Files Copy = 10808333

Time taken by Apache Commons IO Copy = 17971677
 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 裝飾者模式(wrapper): 允許向一個現有的對象添加新的功能,同時又不改變其結構。裝飾器模式是一種用於代替繼承的技術,無需通過繼承增加子類就能擴展對象的新功能。使用對象的關聯關係代替繼承關係,更加靈活,同時避免類型體系的快速膨脹。 示例:英雄學習技能 裝飾者模式有四個角色: 1)抽象構建(Com ...
  • PHP字元串函數是核心的一部分。無需安裝即可使用這些函數 ...
  • 一 ORM簡介 MVC或者MVC框架中包括一個重要的部分,就是ORM,它實現了數據模型與資料庫的解耦,即數據模型的設計不需要依賴於特定的資料庫,通過簡單的配置就可以輕鬆更換資料庫,這極大的減輕了開發人員的工作量,不需要面對因資料庫變更而導致的無效勞動 ORM是“對象 關係 映射”的簡稱。(Objec ...
  • 預設方法 步驟 1 : 什麼是預設方法 預設方法是JDK8新特性,指的是介面也可以提供具體方法了,而不像以前,只能提供抽象方法 Mortal 這個介面,增加了一個 預設方法 revive,這個方法有實現體,並且被聲明為了 default package charactor; public inter ...
  • 一、記憶體分析 代碼:引用可以是局部變數也可以是成員變數 二、對象之間建立關係 二、源碼: D34_husband_and_wife.java 地址: https://github.com/ruigege66/Java/blob/master/D34_husband_and_wife.java​ 2. ...
  • 夢中驚醒 在Tomcat的線程池裡,有這樣一個線程,自打出生後,從來不去幹活兒,有好多次走出線程池“這座大山”去看世界的機會,都被他拱手讓給了弟兄們。弟兄們給他取了個名字叫二師兄。沒錯,好吃懶做,飽了睡,醒了吃。這不,又迷迷糊糊睡著了,還打呼嚕呢。“快起來,起來,幹活去了”,有人在喊他。只見二師兄轉 ...
  • 在上篇文章中 "SpringApplication到底run了什麼(上)" 中,我們分析了下麵這個run方法的前半部分,本篇文章繼續開工 6. 獲取系統屬性 但是這個屬性的作用還真不知道。。 7. 列印banner 8. 根據當前環境創建ApplicationContext 基於咱們的Servlet ...
  • PyCon China 是一年一度的 Python 中國開發者大會,今年上海站國內外大佬雲集,「流暢的 Python」作者、Flask 作者及核心維護者、PyCharm 開發者等等大佬都登臺演講。 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...