您的位置:首页 > 其它

文件的切割与合并

2016-04-03 20:30 447 查看
public class SplitFileDemo{

private static final int SIZE = 1024*1024;

public static void main(String[] args) throw Exception{

File file = new File("c:/a.mp3");

splitFile_2(file);

}

private static void splitFile_2(File file) throw IOExcepion{

//用于读取流关联的文件

FileInputStream fis = new FileInputStream(file);

//定义一个1M的缓冲区

byte[] buf =new byte[SIZE];

//创建目的

FileOutputStream fos = null;

int len=o;

int count=1;

//切割文件时,必须记录住被切割的文件的名字,及切出来的个数,以方便合并

Properties prop = new Properties();

File dir = new File("c:/partfiles");

if(!dir.exists()){

dir.mkdirs();

}

while((len=fis.read(buf)!=-1){

fos = new FileOutputStream(new File(dir,(count++)+".part");

fos.write(buf,0,len);

fos.close();

}

//将被切割的文件的信息保存到prop集合中

prop.setProperty("partcount",count+"");

prop.setProperty("filename",file.getName());

fos =new FileOutputStream(new File(dir,count+".properties");

prop.store(fos,"save file info");

fos.close();

fis.close();

}

}

public class SuffixFilter implements FileNameFilter{

private String suffix;

public SuffixFilter(String suffix){

super();

this.suffix=suffix;

}

public boolean accept(File dir,String name){

return name.endWith(suffix);

}

}

public class MergeFile{

public static void main(String[] args) throws IOException{

File dir = new File("c:\\partfiles");

mergeFile_2(dir);

}

public static void mergeFile_2(File dir) throw IOExcepion{

//获取指定目录下的配置文件

File[] files =dir.listFiles(new SuffixFilter(".properties");

if(files.length!=1)

throw new RuntimeException();

File confile = files[0];

Properties prop = new Properties();

//获取该目录文件中的信息

FileInputStream fis =new FIleInputStream(confile);

prop.load(fis);

String filename = prop.getProperty("filename");

int count = Integer.parseInt(prop.getProperty("partcount");

//获取该目录的所有文件碎片

File[] partFiles = dir.listFIles(new SuffixFilter(".part"));

if(partFiles.length!=(count-1)){

throw new runtimeException(e);

}

//将碎片文件和流对象关联,并存储到集合中

ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();

for(int x=0;x<partFiles.length;x++){

al.add(new FileInputStream(partFile[x]);

}

//将多个流合并成一个序列流

Enumeration<FileInputStream> en = Collections.enumeration(al);

SequenceInputStream sis = new SequenceInputStream(en);

FileOutputStream fos = new FileOutputStream(new File(dir,filename));

byte[] buf = new byte[1024];

int len =0 ;

while((len=sis.read(buf)!=-1){

fos.write(buf,0,len);

}

fos.close();

fis.close();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: