Java 文件分割 和 文件合並


文件切割和文件合並這個問題困擾了我有一段時間了(超過一天沒做粗來)。

找了好多博客,本來想轉載一個來的 結果找不到了。很無奈。

只好自己貼代碼上了。

當然我會盡力好好寫注釋的。

 

文件切割器:

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 import java.io.RandomAccessFile;
 5 import java.util.Scanner;
 6 
 7 public class Main {
 8     public static void main(String[] args) throws FileNotFoundException, IOException {
 9         File sourceFile = new File("ping.mp3");
10 //        System.out.println(sourceFile.exists());
11         Scanner scanner = new Scanner(System.in);
12         int numberOfPieces = 1;        //默認文件切割的數量
13         System.out.println("Enter:");        //提示輸入
14         numberOfPieces = scanner.nextInt();        //輸入
15         scanner.close();        //輸入后就關閉 裝完逼就跑一個道理
16         long fileLength = sourceFile.length() / numberOfPieces;        //分一下每一個小文件的大小
17         byte[] b = new byte[1024];        //這個不解釋 如果看不懂 就去看IO流去吧
18         RandomAccessFile raf1 = new RandomAccessFile(sourceFile, "r");        
19         int len = -1;
20         for(int i = 0; i < numberOfPieces; i++) {
21             String name = sourceFile.getName() + "." + (i+1);
22             File file = new File(name);
23             file.createNewFile();
24             RandomAccessFile raf2 = new RandomAccessFile(file, "rw");
25             while((len = raf1.read(b)) != -1) {
26                 raf2.write(b, 0, len);        //我覺的這樣寫比raf2.write(b);高明一些
27                 if(raf2.length() > fileLength)        //如果太大了就不在這個子文件寫了 換下一個
28                     break;
29             }
30             raf2.close();
31         }
32         raf1.close();
33     }
34 }

 

文件合並器:

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 import java.io.RandomAccessFile;
 5 
 6 //文件合並 ping.n
 7 public class Main {
 8     public static void main(String[] args) throws FileNotFoundException, IOException {
 9         File[] files = new File[10];
10         String name = "ping.";
11         File file = new File("ping.mp3");
12         file.createNewFile();
13         RandomAccessFile in = new RandomAccessFile(file, "rw");
14         in.setLength(0);
15         in.seek(0);
16         byte[] bytes = new byte[1024];
17         int len = -1;
18         for(int i = 0; i < files.length; i++) {
19             files[i] = new File(name + (i + 1));
20             //System.out.println(files[i].exists());
21             RandomAccessFile out = new RandomAccessFile(files[i], "rw");
22             while((len = out.read(bytes)) != -1) {
23                 in.write(bytes, 0, len);
24             }
25             out.close();
26         }
27         in.close();
28     }
29 }

文件合並器就不寫注釋了,因為這是一個逆過程。(懶癌附體)

 


免責聲明!

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



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