1. 程式人生 > 程式設計 >java合併多個檔案的兩種方法

java合併多個檔案的兩種方法

在java多個執行緒下載檔案或處理較大檔案是可能會切分成多個檔案,處理完成後需要合併成一個檔案。

Java中合併子檔案最容易想到的就是利用BufferedStream進行讀寫。

利用BufferedStream合併多個檔案

public static boolean mergeFiles(String[] fpaths,String resultPath) {
  if (fpaths == null || fpaths.length < 1 || TextUtils.isEmpty(resultPath)) {
    return false;
  }
  if (fpaths.length == 1) {
    return new File(fpaths[0]).renameTo(new File(resultPath));
  }
 
  File[] files = new File[fpaths.length];
  for (int i = 0; i < fpaths.length; i ++) {
    files[i] = new File(fpaths[i]);
    if (TextUtils.isEmpty(fpaths[i]) || !files[i].exists() || !files[i].isFile()) {
      return false;
    }
  }
 
  File resultFile = new File(resultPath);
 
  try {
    int bufSize = 1024;
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(resultFile));
    byte[] buffer = new byte[bufSize];
 
    for (int i = 0; i < fpaths.length; i ++) {
      BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(files[i]));
      int readcount;
      while ((readcount = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,readcount);
      }
      inputStream.close();
    }
    outputStream.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
    return false;
  } catch (IOException e) {
    e.printStackTrace();
    return false;
  }
 
  for (int i = 0; i < fpaths.length; i ++) {
    files[i].delete();
  }
 
  return true;
}

利用nio FileChannel合併多個檔案

BufferedStream的合併操作是一個迴圈讀取子檔案內容然後複製寫入最終檔案的過程,此過程會從檔案系統中讀取資料到記憶體中,之後再寫入檔案系統,比較低效。

一種更高效的合併方式是利用Java nio庫中FileChannel類的transferTo方法進行合併。此方法可以利用很多作業系統直接從檔案快取傳輸位元組的能力來優化傳輸速度。

實現方法:

public static boolean mergeFiles(String[] fpaths,String resultPath) {
  if (fpaths == null || fpaths.length < 1 || TextUtils.isEmpty(resultPath)) {
    return false;
  }
  if (fpaths.length == 1) {
    return new File(fpaths[0]).renameTo(new File(resultPath));
  }
 
  File[] files = new File[fpaths.length];
  for (int i = 0; i < fpaths.length; i ++) {
    files[i] = new File(fpaths[i]);
    if (TextUtils.isEmpty(fpaths[i]) || !files[i].exists() || !files[i].isFile()) {
      return false;
    }
  }
 
  File resultFile = new File(resultPath);
 
  try {
    FileChannel resultFileChannel = new FileOutputStream(resultFile,true).getChannel();
    for (int i = 0; i < fpaths.length; i ++) {
      FileChannel blk = new FileInputStream(files[i]).getChannel();
      resultFileChannel.transferFrom(blk,resultFileChannel.size(),blk.size());
      blk.close();
    }
    resultFileChannel.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
    return false;
  } catch (IOException e) {
    e.printStackTrace();
    return false;
  }
 
  for (int i = 0; i < fpaths.length; i ++) {
    files[i].delete();
  }
 
  return true;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。