Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發——合併檔案的幾種方式

編輯:關於 Android 程式設計

本文介紹合併檔案的幾種方式,並以合併 amr 語音檔為例說明流程。amr 格式的檔案頭為 6 位元組,因此合併時需扣除第一個檔案以外其他檔案的檔案頭。

注意:不同格式的檔案頭長度不同,合併時應依格式扣除對應的檔案頭。

步驟一:取得待合併檔案並建立輸出檔

List tempFiles = new ArrayList(); File finalFile;
private File getFile(boolean isTempFile) { finalFile = null; if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.w("Waring", "檢測到你的手機沒有插入SD卡,請插入SD後再試!"); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault()); String fileName = simpleDateFormat.format(new Date()) + ".amr"; if (isTempFile) { fileName = "temp" + fileName; } try { File parentFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/" + "Recorder"); if (!parentFile.exists() || parentFile == null) { parentFile.mkdirs(); } finalFile = new File(parentFile, fileName); } catch (IOException e) { e.printStackTrace(); } return finalFile; }

步驟二:合併檔案

方式一:使用 FileOutputStream 與 FileInputStream,遍歷每個暫存檔並扣除 amr 的 6 位元組檔頭:

public void mergeFiles1() { if (tempFiles.isEmpty()) return; File realFile = getFile(false); try { FileOutputStream fos = new FileOutputStream(realFile); for (int i = 0; i < tempFiles.size(); i++) { FileInputStream fis = new FileInputStream(tempFiles.get(i)); byte[] tmpBytes = new byte[fis.available()]; int length = tmpBytes.length; if (i == 0) { while (fis.read(tmpBytes) != -1) { fos.write(tmpBytes, 0, length); } } else { while (fis.read(tmpBytes) != -1) { fos.write(tmpBytes, 6, length - 6); } } fos.flush(); fis.close(); } fos.close(); } catch (Exception e) { e.printStackTrace(); } for (File file : tempFiles) { if (file.exists()) { file.delete(); } } }

方式二:使用 FileChannel 的 transferTo 直接搬移位元組(實務上仍應扣除檔頭):

public void mergeFiles2() { File realFile = getFile(false); FileChannel mFileChannel; try { FileOutputStream fos = new FileOutputStream(realFile); mFileChannel = fos.getChannel(); FileChannel inFileChannel; for (File file : tempFiles) { inFileChannel = new FileInputStream(file).getChannel(); inFileChannel.transferTo(0, inFileChannel.size(), mFileChannel); inFileChannel.close(); } fos.close(); mFileChannel.close(); } catch (Exception e) { e.printStackTrace(); } }

方式三:使用 RandomAccessFile,透過 seek 跳過 amr 檔頭:

public void mergeFiles3() { try { File realFile = getFile(false); FileOutputStream fos = new FileOutputStream(realFile); RandomAccessFile ra = null; for (int i = 0; i < tempFiles.size(); i++) { ra = new RandomAccessFile(tempFiles.get(i), "r"); if (i != 0) { ra.seek(6); } byte[] buffer = new byte[1024 * 8]; int len = 0; while ((len = ra.read(buffer)) != -1) { fos.write(buffer, 0, len); } } ra.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } }

三種方式各有適用情境:串流寫法直觀通用,FileChannel 適合大量資料搬移,RandomAccessFile 則便於精確控制讀取位置。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved