Java实现多段小视频合成一个视频
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class MergeVideo {
public static List getAllFilesAndDir(String path) {
File root = new File(path);
List files = new ArrayList();
if (!root.isDirectory()) {
files.add(root);
} else {
File[] subFiles = root.listFiles();
for (File f : subFiles) {
files.addAll(getAllFilesAndDir(f.getAbsolutePath()));
}
}
return files;
}
public static List<File> getAllFiles(String path) {
File root = new File(path);
if(root.getName().contains("DS_Store")) {
System.out.println(root.getName());
}
if (root.isDirectory()) {
return Arrays.asList(root.listFiles()).stream().filter(a -> !a.getName().endsWith(".DS_Store")).collect(Collectors.toList());
}
return new ArrayList();
}
public static boolean MergeFiles(List<File> listFiles, String destFullPath) {
boolean flag = true;
BufferedOutputStream bos = null;
BufferedReader br = null;
try {
FileInputStream fis;
FileOutputStream fos = new FileOutputStream(destFullPath);
byte buffer[] = new byte[1024 * 1024 * 2];
for (File srcFile : listFiles) {
if (srcFile.isFile() && !srcFile.getName().endsWith(".DS_Store")) {
System.out.println(srcFile.getName() + "是合法文件,开始合并");
try {
fis = new FileInputStream(srcFile);
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
} finally {
if (br != null) {
br.close();
}
}
} else {
System.out.println(srcFile.getName() + "文件不满足合并格式!");
}
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
flag = false;
} catch (IOException e) {
e.printStackTrace();
flag = false;
} finally {
try {
if (bos != null) {
bos.close();
} if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
public static void main(String[] args) {
String srcPath = "/Users/srcPath";
String destName = "mergedVideo.mp4";
String destFullPath = "/Users/destFileDir" + destName;
List<File> files = getAllFiles(srcPath);
Collections.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if (o1.isDirectory() && o2.isFile())
return -1;
if (o1.isFile() && o2.isDirectory())
return 1;
Integer o1Name =Integer.valueOf(o1.getName());
Integer o2Name =Integer.valueOf(o2.getName());
return o1Name.compareTo(o2Name);
}
});
for (File file : files) {
System.out.println(file.getName());
}
boolean flag = MergeFiles(files, destFullPath);
System.out.println("合并完成的标记:" + flag);
}
}