package DeliverFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class DeliverFile2 {
public static void main(String[] args) {
cut();
merge();
}
//拆分文件
public static void cut() {
File file = new File("G:\\test\\source.avi");
int num = 10;//分割文件的數量
long lon = file.length() / 10L + 1L;//使文件字節數+1,保證取到全部的字節
try {
RandomAccessFile raf1 = new RandomAccessFile(file, "r");
byte[] bytes = new byte[1024];//值設置越小,則各個文件的字節數越接近平均值,但效率會下降,這裏折中,取1024
int len = -1;
for (int i = 0; i < 10; i++) {
String name = "G:\\test2\\source" + i + ".avi";
File file2 = new File(name);
RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
while ((len = raf1.read(bytes)) != -1){//讀到文件末尾時,len返回-1,結束循環
raf2.write(bytes, 0, len);
if (raf2.length() > lon)//當生成的新文件字節數大於lon時,結束循環
break;
}
raf2.close();
}
raf1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//合併文件
public static void merge() {
File file = new File("G:\\test2\\new.avi");
try {
RandomAccessFile target = new RandomAccessFile(file, "rw");
for (int i = 0; i < 10; i++) {
File file2 = new File("G:\\test2\\source" + i + ".avi");
RandomAccessFile src = new RandomAccessFile(file2, "r");
byte[] bytes = new byte[1024];//每次讀取字節數
int len = -1;
while ((len = src.read(bytes)) != -1) {
target.write(bytes, 0, len);//循環賦值
}
src.close();
}
target.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}java