一、切割文件代碼如下:
需求:將一個媒體文件切割成多個碎片(每個碎片的大小為1M),并添加配置說明文件
1.創建(指定)一個文件夾,用于保存切割出來的碎片
2.創建源文件對象,并傳入一個輸入流對象
3.創建一個緩沖區為1M
4.創建一個輸入流對象并將源文件對象傳入,創建一個輸出流對象引用
5.每個緩沖區獲取到碎片時,使用輸出對應流對象寫入到一個新的文件
6.寫相應的信息到配置文件
實現代碼:
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
|
public class SplitFileTest { public static void main(String[] args) throws IOException { /** * 需求:將一個媒體文件切割成多個碎片(每個碎片的大小為1M),并添加配置說明文件 * 1.創建(指定)一個文件夾,用于保存切割出來的碎片 * 2.創建源文件對象,并傳入一個輸入流對象 * 3.創建一個緩沖區為1M * 4.創建一個輸入流對象并將源文件對象傳入,創建一個輸出流對象引用 * 5.每個緩沖區獲取到碎片時,使用輸出對應流對象寫入到一個新的文件 * 6.寫相應的信息到配置文件 */ File partDir = new File( "F:\\partsDir" ); File src = new File( "F:\\周杰倫 - 簡單愛.mp3" ); splitFile(src,partDir); } private static void splitFile(File src, File partDir) throws IOException { if (!partDir.exists()){ partDir.mkdirs(); } byte [] buf = new byte [ 1024 * 1024 ]; FileInputStream fis = new FileInputStream(src); FileOutputStream fos = null ; int len = 0 ; int count = 1 ; while ((len=fis.read(buf)) != - 1 ){ fos = new FileOutputStream( new File(partDir, "簡單愛-part" +(count++))); fos.write(buf, 0 ,len); fos.close(); } String filename = src.getName(); int partCount = count; fos = new FileOutputStream( new File(partDir,count+ ".properties" )); //創建一個屬性集。 Properties prop = new Properties(); //將配置信息存儲到屬性集中 prop.setProperty( "filename" ,src.getName()); prop.setProperty( "partCount" ,Integer.toString(partCount)); //將屬性集中的信息持久化 prop.store(fos, "part file info" ); fos.close(); fis.close(); } } |
二、合并文件代碼如下:
需求:使用SequenceInputStream類來合并碎片文件
1.創建一個list集合,來保存指定文件夾碎片流集合
2.用集合工具類方法Collections.enumeration()方法將list集合轉換為Enumeration
3.新建一個SequenceInputStream流對象,并傳入第2步的Enumeration
4.創建一個輸出流對象,創建緩沖區循環寫第3步SequenceInputStream讀取的內容
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
|
public class MergeFileTest { public static void main(String[] args) throws IOException { /** * 需求:使用SequenceInputStream類來合并碎片文件 * 1.創建一個list集合,來保存指定文件夾碎片流集合 * 2.用集合工具類方法Collections.enumeration()方法將list集合轉換為Enumeration * 3.新建一個SequenceInputStream流對象,并傳入第2步的Enumeration * 4.創建一個輸出流對象,創建緩沖區循環寫第3步SequenceInputStream讀取的內容 */ File partDir = new File( "F:\\partsDir" ); List<FileInputStream> list = new ArrayList<FileInputStream>(); for ( int i= 1 ;i< 12 ;i++){ FileInputStream fis = new FileInputStream( new File(partDir, "簡單愛-part" +i)); list.add(fis); } Enumeration<FileInputStream> en = Collections.enumeration(list); SequenceInputStream sis = new SequenceInputStream(en); FileOutputStream fos = new FileOutputStream( new File(partDir, "000.mp3" )); byte [] buf = new byte [ 1024 ]; int len = 0 ; while ((len=sis.read(buf)) != - 1 ){ fos.write(buf, 0 ,len); } fos.close(); sis.close(); } } |
以上就是關于java 文件切割和合并的實例詳解,大家如果有疑問可以留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:https://my.oschina.net/daladida/blog/1484032