实现一个文件的分割
对一个文件进行分割,把要分割的文件和分割成多大的传到方法divison里,先判断文件是不是为空,如果为空直接就结束方法return,如果不为空就 计算一下 把文件分割成几个小文件,用文件大小对cutSize小文件的大小取余,如果能够被整除,小文件的个数就是file.length()/cutSize(文件大小除以小文件的大小),如果不能被整除就,小文件的个数就是file.length()/cutSize+1(这个1用来接收多余的一部分,不够一个cutSize).
然后new一个BufferderInputStream缓冲流用来读取文件,在定义一个BufferedOutputStream用来写文件,因为小文件的名字每次都不同,所以先不实例化。new 一个byte数组表示每次写书文件的字节。
public class FileDivison {
private static void divison(File file,long cutSize) {
if(file == null)return ;
int num = file.length()%cutSize==0 ? (int)(file.length()/cutSize):(int)(file.length()/cutSize+1);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream out = null;
byte[] bytes = null;
int len = -1;
int count = 0;
for(int i =0;i<num;i++) {
out = new BufferedOutputStream(new FileOutputStream("D:\\tools\\test1\\"+(i+1)+"_temp"+".wmv"));
if(cutSize<1024) {
bytes = new byte[(int)cutSize];
count = 1;
}else {
bytes = new byte[1024];
count = (int)cutSize/1024;
}
while(count>0&&(len = in.read(bytes))!=-1) {
out.write(bytes);
out.flush();
count--;
}
if(cutSize%1024!=0) {
bytes = new byte[(int)cutSize%1024];
len = in.read(bytes);
out.flush();
}
out.close();
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File file = new File("D:\\tools\\qianfeng\\Day11\\Java_Day11\\视频\\Video_2018-08-08_103749.wmv");
divison(file, 1024*1024*20);
}
}