首先,进行文件分割
File savePath = new File("Part");
File moveFile = new File("001.mp4");
cutFile(savePath, moveFile);
private static void cutFile(File parent, File file) throws IOException {
if (!file.exists()) {
System.out.println("文件不存在");
return;
}
parent.mkdirs();
// 使用缓冲装饰类来读取视频文件数据
BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file));
// 创建一个字节缓冲数组
byte[] buff = new byte[1024 * 1024 * 10];
int num = 0;
int i = 1;
while ((num = buffIn.read(buff)) != -1) {
File saveP = new File(parent, i + ".part");
FileOutputStream out = new FileOutputStream(saveP);
i++;
out.write(buff, 0, num);
out.flush();
out.close();
}
Properties pro = new Properties();
pro.setProperty("filename", file.getName());
pro.setProperty("partCount", i + "");
FileOutputStream out = new FileOutputStream("info.properties");
pro.store(out, "partCount");
out.close();
buffIn.close();
}
下面视频合并
File savePath = new File("Part");
mergePartFile(savePath);
//视频合并
private static void mergePartFile(File savePath) throws IOException {
// 1.验证文件路径
if (!savePath.exists()) {
throw new RuntimeException("碎片路径不正确");
}
// 2.先获取碎片文件的信息配置数据
Properties pro = new Properties();
// 3.创建一个配置文件流对象
File[] proFile = savePath.listFiles(new FileNameFileterWithEnd(".properties"));
if (proFile.length != 1) {
System.out.println("碎片文件配置信息异常,无法正确合并");
return;
}
// 创建流获取数据
FileInputStream proIn = new FileInputStream(proFile[0]);
pro.load(proIn);
// 获取文件名和碎片数量
String name = pro.getProperty("filename");
int count = Integer.parseInt(pro.getProperty("partCount"));
//
System.out.println(name + ":" + count);
File[] parts = savePath.listFiles(new FileNameFileterWithEnd(".part"));
if (parts.length != count - 1) {
System.out.println("要合并的碎片数量不正确");
return;
}
// 合并
// 创建一个保存输入流的集合
ArrayList<FileInputStream> partsIn = new ArrayList<>();
for (File file : parts) {
partsIn.add(new FileInputStream(file));
}
// 将集合转变为枚举
Enumeration<FileInputStream> enumIn = Collections.enumeration(partsIn);
// 创建序列流对象
SequenceInputStream sIn = new SequenceInputStream(enumIn);
BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(new File(savePath, name)));
byte[] buff = new byte[1024];
int num = 0;
while ((num = sIn.read(buff)) != -1) {
bOut.write(buff, 0, num);
bOut.flush();
}
bOut.close();
sIn.close();
for (FileInputStream fileInputStream : partsIn) {
fileInputStream.close();
}
}
该方法只能合并10个以内文件,10个以上文件需要对文件名进行排序后合并,否则数据会乱