JAVA中用流进行文件分割

时间:2022-02-24 23:08:41
package com.google.javase.io;
/**
 * 文件分割
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class FileDivisionAndMerge {
	//文件的分割
	private static void Division(File targetfile,long cutsize) {
		//计算总分割的文件数
		int num = (targetfile.length()%cutsize==0
				?(int)(targetfile.length()/cutsize):(int)(targetfile.length()/cutsize+1));
		try {
			InputStream in = new FileInputStream(targetfile);
			BufferedInputStream bis = new BufferedInputStream(in);
			BufferedOutputStream bos = null;
			byte[] bytes = null;  //每次要读取的文件字节数
			int len = -1;
			int count = 0;   //文件分割次数
			for(int i=0; i<num; i++) {
				bos = new BufferedOutputStream(new 
						FileOutputStream(new File("E:\\javaseio\\my\\"+"第"+(i+1)+"-temp-"+targetfile.getName())));
				if(cutsize<=1024) {
					bytes = new byte[(int) cutsize];
					count = 1;
				}else {
					bytes = new byte[1024];
					count = (int) (cutsize/1024);
				}
				while(count>0&&(len=bis.read(bytes))!=-1) {
					bos.write(bytes,0,len);
					bos.flush();
					count--;
				}
				if(cutsize%1024!=0) {
					bytes = new byte[(int) (cutsize%1024)];
					len = bis.read();
					bos.write(bytes, 0, len);
					bos.flush();
					bos.close();
				}
				
			}
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		Division(new File("e:\\javaseio\\my\\me\\第01章 Java开发入门 01 计算机基本概念与dos命令.avi"),1024*1024*10);
	}

}
源文件所在位置:
e:\\javaseio\\my\\me\\第01章 Java开发入门 01 计算机基本概念与dos命令.avi

JAVA中用流进行文件分割

实现分割后:

JAVA中用流进行文件分割

JAVA中用流进行文件分割