IO流_文件切割与合并

切割可以分两种方式:按文件个数切,按文件大小来切(建议用这种方式,因为按个数的话,有可能文件非常大)

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 public class SplitFileDemo {
 7     private static final int SIZE = 1024*1024;//1M=1024*1024个字节
 8 
 9     public static void main(String[] args) throws IOException {
10         File file = new File("F:\\jian.avi");
11         splitFileDemo(file);
12         
13     }
14     public static void splitFileDemo(File file) throws IOException {
15         
16         //用读取流关联一个文件
17         FileInputStream fis = new FileInputStream(file);
18         //定义一个1M的缓冲区
19         byte[] buf = new byte[SIZE];
20         
21         //创建目的
22         FileOutputStream fos = null;
23         
24         File dir = new File("F:\\partfiles");
25         
26         if(!dir.exists()){
27             dir.mkdirs();
28         }
29         
30         int count = 1;
31         int len = 0;
32         while((len = fis.read(buf))!=-1){
33             fos = new FileOutputStream(new File(dir,(count++)+".part"));//扩展名可以依据软件的需求来定义,但不要是txt这些扩展名,因为切割完的文件不能直接读取
34             fos.write(buf,0,len);
35         }
36         fos.close();
37         fis.close();
38     }
39 }

 

合并:

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.SequenceInputStream;
 6 import java.util.ArrayList;
 7 import java.util.Collections;
 8 import java.util.Enumeration;
 9 import java.util.Properties;
10 
11 public class MergeFile {
12     public static void main(String[] args) throws IOException {
13 
14         File dir = new File("c:\\partfiles");
15         
16         mergeFile(dir);
17     }
18     public static void mergeFile(File dir) throws IOException{
19         
20         
21         ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
22         
23         for(int x=1; x<=3 ;x++){
24             al.add(new FileInputStream(new File(dir,x+".part")));
25         }
26         
27         Enumeration<FileInputStream> en = Collections.enumeration(al);
28         SequenceInputStream sis = new SequenceInputStream(en);
29         
30         FileOutputStream fos = new FileOutputStream(new File(dir,"1.bmp"));
31         
32         byte[] buf = new byte[1024];
33         
34         int len = 0;
35         while((len=sis.read(buf))!=-1){
36             fos.write(buf,0,len);
37         }
38         
39         fos.close();
40         sis.close();
41         
42     }
43 
44 }

 

 

转载于:https://www.cnblogs.com/LO-ME/p/3596380.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值