學習文件的輸入輸出流,自己做一個小的示例,對文件進行分割和合并。
下面是代碼:
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
package com.dufy.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; /** * 文件的切割和合并 * 1.要切割和合并文件:主要考慮的就是文件的源地址,目標地址,暫存文件地址和文件名稱 * 2.切割文件:判斷給的暫存地址是否存在,不存在,則創建;從源地址中讀出文件,按照給定的大小進行文件的切割操作放入暫存地址中 * 3.合并文件:判斷給定的目標地址是否存在,不存在,則創建;定義List集合將暫存地址中的文件全部讀取出來,放到list集合中 * 然后使用Enumeration列舉出所有文件,合并流合并文件 * 最后寫入到目標的地址中 * 注:本例子中所有的異常都采用拋出的方式處理 * @author aflyun * */ public class TestFileCutUnion { public static void main(String[] args) throws IOException { String fSrc = "D:/1.jpg" ; //源文件的目錄 String fDir = "D:/1" ; //目標文件的目錄 String fTemp = "D:/2" ; //暫存文件的目錄 File srcFile = new File(fSrc); File dirFile = new File(fDir); File tempFile = new File(fTemp); String fileName = srcFile.getName(); //獲取文件的名稱 cutFile(srcFile,tempFile); //調用分割方法 unionFile(dirFile,tempFile,fileName); //調用合并方法 } /** * 切割文件 * @param srcFile * @param tempFile * @throws IOException */ public static void cutFile(File srcFile, File tempFile) throws IOException { //讀取源地址文件 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = null ; //是否為文件,不是就創建 if (!tempFile.isFile()){ tempFile.mkdirs(); } byte [] b = new byte [ 100 ]; int len = 0 ; int count = 0 ; while ((len=fis.read(b)) != - 1 ){ int num = count++; //寫入暫存地址目錄中 fos = new FileOutputStream( new File(tempFile, num+ ".part" )); fos.write(b, 0 , len); } fos.flush(); fos.close(); fis.close(); System.out.println( "分割完成!" ); } /** * 合并文件 * @param dirFile * @param tempFile * @param fileName * @throws IOException */ public static void unionFile(File dirFile, File tempFile, String fileName) throws IOException { //判斷目標地址是否存在,不存在則創建 if (!dirFile.isFile()){ dirFile.mkdirs(); } List<FileInputStream> list = new ArrayList<FileInputStream>(); //獲取暫存地址中的文件 File[] files = tempFile.listFiles(); for ( int i = 0 ; i < files.length; i++) { //用FileInputStream讀取放入list集合 list.add( new FileInputStream( new File(tempFile, i+ ".part" ))); } //使用 Enumeration(列舉) 將文件全部列舉出來 Enumeration<FileInputStream> eum = Collections.enumeration(list); //SequenceInputStream合并流 合并文件 SequenceInputStream sis = new SequenceInputStream(eum); FileOutputStream fos = new FileOutputStream( new File(dirFile, fileName)); byte [] by = new byte [ 100 ]; int len; while ((len=sis.read(by)) != - 1 ){ fos.write(by, 0 , len); } fos.flush(); fos.close(); sis.close(); System.out.println( "合并完成!" ); } } |
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/u010648555/article/details/50085863