IO综合练习--文件切割和文件合并

时间:2023-03-09 16:13:38
IO综合练习--文件切割和文件合并

有时候一个视频文件或系统文件太大了,上传和下载可能会受到限制,这时可以用文件切割器把文件按大小切分为文件碎片,

等到要使用这个文件了,再把文件碎片合并成原来的文件即可。下面的代码实现了文件切割和文件合并功能。

一、切割文件

* 切割文件,按大小切割
* 把被切割的文件名和切割成的文件碎片数以键值对的形式写在配置文件中,
* 这要用到Properties集合
* 以便文件合并时可以读取并使用这些信息

 public class SplitTest {

     private static final int SIZE = 1024*1024;
public static void main(String[] args) throws IOException {
File file=new File("F:\\background.bmp");
splitFile(file);
}
public static void splitFile(File file) throws IOException{
//建立字节读取流
FileInputStream fis=new FileInputStream(file);
byte[] buf=new byte[SIZE];//建立1M的缓冲区
//建立碎片文件,所要放入的路径
File dir=new File("F:\\partFiles");
if(!dir.exists()){//目录不存在
dir.mkdirs();//则创建
}
//建立字节写入流
FileOutputStream fos=null;
int len=0;
int count=1;
while((len=fis.read(buf))!=-1){//从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
//在某些输入可用之前,此方法将阻塞。
fos=new FileOutputStream(new File(dir,(count++)+".part"));
fos.write(buf, 0, len);//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
fos.close();
}
//把切割信息存储到配置文件中
fos=new FileOutputStream(new File(dir,count+".properties"));
Properties prop=new Properties();
prop.setProperty("partCount", (count-1)+"");
prop.setProperty("fileName", file.getName());
prop.store(fos, "split info in file");
fis.close();
fos.close();
}
}

二、合并文件

 //合并文件
public class MergeFileTest { public static void main(String[] args) throws IOException {
File dir=new File("F:\\partFiles");
mergeFiles(dir);
}
public static void mergeFiles(File file) throws IOException{
//从配置文件中获取信息
//先做健壮性判断 判断配置文件数量是否正确
File[] files=file.listFiles(new SuffixFilter(".properties"));
if(files.length!=1){
throw new RuntimeException("当前目录下没有配置文件或者配置文件不唯一");
}
//获取信息
File configFile=files[0];//获取配置文件对象
Properties prop=new Properties();
FileInputStream fis=new FileInputStream(configFile);
prop.load(fis); String fileName=prop.getProperty("fileName");
int count=Integer.parseInt(prop.getProperty("partCount")); //判断此目录下的文件碎片数是否正确
File[] partFiles=file.listFiles(new SuffixFilter(".part"));
if(partFiles.length!=count){
throw new RuntimeException("文件碎片数不正确,请重新下载");
} ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();
//把读取流添加到集合中去
for(int i=0;i<count;i++){
al.add(new FileInputStream( partFiles[i]));
}
Enumeration<FileInputStream> en=Collections.enumeration(al);
//建立序列流
SequenceInputStream sis=new SequenceInputStream(en); //建立写入流
FileOutputStream fos=new FileOutputStream(new File(file,fileName));
byte[] buf=new byte[1024];
int len=0;
while((len=sis.read(buf))!=-1){
fos.write(buf, 0, len);
}
sis.close();
fos.close();
}
}
 public class SuffixFilter implements FilenameFilter {
private String suffix;
public SuffixFilter(String suffix) {
super();
this.suffix = suffix;
}
@Override
public boolean accept(File arg0, String arg1) {
// TODO Auto-generated method stub
return arg1.endsWith(suffix);
} }

不足之处:

1.没有图形化界面,不好操作。

2.应该把细化一些小的功能写成方法,而不是都写在一个大的方法中。