Java文件合並


文件分割與合並是一個常見需求,比如:上傳大文件時,可以先分割成小塊,傳到服務器后,再進行合並。很多高大上的分布式文件系統(比如:google的GFS、taobao的TFS)里,也是按block為單位,對文件進行分割或合並。

單線程實現:

 1 package FileDemo;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.SequenceInputStream;
 8 import java.util.ArrayList;
 9 import java.util.Collections;
10 import java.util.Enumeration;
11 
12 public class MergeFileDemo {
13 
14     //定義緩沖區的大小
15     private static final int size = 1024 * 1024;
16 
17     /**
18      * @param args
19      * @throws IOException
20      */
21     public static void main(String[] args) throws IOException {
22 
23         File srcFile = new File("D:\\destFile");
24         MergeFileTest(srcFile);
25     }
26 
27     private static void MergeFileTest(File srcFile) throws IOException {
28         ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
29         for (int x = 1; x <= 4; x++) {
30             // 將要合並的碎片封裝成對象
31             al.add(new FileInputStream(new File(srcFile, x + ".part")));
32         }
33         Enumeration<FileInputStream> en = Collections.enumeration(al);
34         SequenceInputStream sis = new SequenceInputStream(en);
35         // 將合成的文件封裝成一個文件對象
36         FileOutputStream fos = new FileOutputStream(new File(srcFile, "1.mp3"));
37         int len = 0;
38         byte buf[] = new byte[size];
39         while ((len = sis.read(buf)) != -1) {
40             fos.write(buf, 0, len);
41         }
42         fos.close();
43         sis.close();
44     }
45 
46 }

 


免責聲明!

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



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