文件分割應該算一個比較實用的功能,舉例子說明吧比如說:你有一個3G的文件要從一臺電腦Copy到另一臺電腦, 但是你的存儲設備(比如SD卡)只有1G ,這個時候就可以把這個文件切割成3個1G的文件 ,分開復制, 最后把三個文件合并, 這樣就解決問題了 ;再比如說, 你有一個上百M的文件要上傳到FTP ,但是這個FTP限制你單個文件不能超過10M 這時候也可以用文件分割的辦法解決問題。既然分割了,那么在我們再次使用的時候就需要合并了,今天我們就通過Java代碼實現文件分裂與合并的能。
現在通過演示我本機的一個文件來演示,文件目錄為:E:\eclipse-jee-juno-win32.zip(今天就把大家痛恨的eclipse好好玩一下):
下圖為分割前的情況:
分割后的情況為:
Java分割文件的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
//文件分割的方法(方法內傳入要分割的文件路徑以及要分割的份數) private static void splitFileDemo(File src, int m) { if (src.isFile()) { //獲取文件的總長度 long l = src.length(); //獲取文件名 String fileName = src.getName().substring( 0 , src.getName().indexOf( "." )); //獲取文件后綴 String endName = src.getName().substring(src.getName().lastIndexOf( "." )); System.out.println(endName); InputStream in = null ; try { in = new FileInputStream(src); for ( int i = 1 ; i <= m; i++) { StringBuffer sb = new StringBuffer(); sb.append(src.getParent()).append( "\\" ).append(fileName) .append( "_data" ).append(i).append(endName); System.out.println(sb.toString()); File file2 = new File(sb.toString()); //創建寫文件的輸出流 OutputStream out = new FileOutputStream(file2); int len = - 1 ; byte [] bytes = new byte [ 10 * 1024 * 1024 ]; while ((len = in.read(bytes))!=- 1 ) { out.write(bytes, 0 , len); if (file2.length() > (l / m)) { break ; } } out.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
Java合并文件的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
//文件合并的方法(傳入要合并的文件路徑) private static void joinFileDemo(String... src) { for ( int i = 0 ; i < src.length; i++) { File file = new File(src[i]); String fileName = file.getName().substring( 0 , file.getName().indexOf( "_" )); String endName = file.getName().substring(file.getName().lastIndexOf( "." )); StringBuffer sb = new StringBuffer(); sb.append(file.getParent()).append( "\\" ).append(fileName) .append(endName); System.out.println(sb.toString()); try { //讀取小文件的輸入流 InputStream in = new FileInputStream(file); //寫入大文件的輸出流 File file2 = new File(sb.toString()); OutputStream out = new FileOutputStream(file2, true ); int len = - 1 ; byte [] bytes = new byte [ 10 * 1024 * 1024 ]; while ((len = in.read(bytes))!=- 1 ) { out.write(bytes, 0 , len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println( "文件合并完成!" ); } |
寫之前覺得挺復雜,寫完之后覺得也就那樣,大家也可以練練手。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/qq_35101189/article/details/53793194