Java学习之字节流-文件分割合并--2015-2-28

文件的分割合并

public class Test {

	private static int size=1024;
	
	public static void main(String[] args) throws Exception {
		//切割的文件
		File srcfile = new File("D:/workspace/Test/脸萌.JPG");
		//切割文件的存放目录
		File src = new File("");
		//源文件目录
		String descpath = "D:/workspace/parts";
		//还原文件的存放路径
		File desc = new File("D:/workspace");
		//还原文件名称
		String name = srcfile.getName();
		
		//文件切割
		splitFile(srcfile,descpath);
		//文件合并
		unionfile(desc,descpath,name);
	}
	
	public static void unionfile(File desc,String descpath,String name) throws Exception{
		ArrayList list = new ArrayList();
		File src = new File(descpath);
		File[] files = src.listFiles(new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				return new File(dir,name).isFile() && name.endsWith(".part");
			}
		});
		
		for(int i=1;i<=files.length;i++){
			list.add(new FileInputStream(new File(src,i+".part")));
		}
		Enumeration en = Collections.enumeration(list);
		SequenceInputStream sis = new SequenceInputStream(en);
		FileOutputStream fos = new FileOutputStream(new File(desc,name));
		
		byte[] by = new byte[1024];
		int len=0;
		while((len = sis.read(by))!=-1){
			fos.write(by,0,len);
		}
		fos.flush();
		fos.close();
		sis.close();
	}
	
	//文件切割
	public static void splitFile(File file,String descpath) throws Exception{
		FileInputStream is = new FileInputStream(file);
		FileOutputStream os = null;
		
		File dir = new File(descpath);
		if(!dir.isFile()){
			dir.mkdirs();
		}
			
		byte[] car = new byte[size];
		int len =0;
		int count =1;
		while((len=is.read(car))!=-1){
			int num = count++;
			os = new FileOutputStream(new File(dir,num+".part"));
			os.write(car,0,len);
		}
		os.flush();
		os.close();
		is.close();
	}
}


你可能感兴趣的:(java-学习)