原文地址:https://blog.csdn.net/chenyun19890626/article/details/54631817
原理很簡單就是把多個視頻文件的內容按順序寫到一個視頻文件中
代碼如下:
public static void CombineFile(String path,String tar) throws Exception {
try {
File dirFile = new File(path);
FileInputStream fis;
FileOutputStream fos = new FileOutputStream(tar);
byte buffer[] = new byte[1024 * 1024 * 2];//一次讀取2M數據,將讀取到的數據保存到byte字節數組中
int len;
if(dirFile.isDirectory()) { //判斷file是否為目錄
String[] fileNames = dirFile.list();
Arrays.sort(fileNames, new StringComparator());//實現目錄自定義排序
for (int i = 0;i<fileNames.length ;i++){
System.out.println("D:\\tempfile\\"+fileNames[i]);
fis = new FileInputStream("D:\\tempfile\\"+fileNames[i]);
len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);//buffer從指定字節數組寫入。buffer:數據中的起始偏移量,len:寫入的字數。
}
fis.close();
}
}
fos.flush();
fos.close();
}catch (IOException e){
e.printStackTrace();
} finally {
System.out.println("合並完成!");
}
}
在讀取要合並的文件時,需要按拆分后的順序讀取文件,這是就需要文件自定義目錄排序
原文地址:https://blog.csdn.net/iamaboyy/article/details/9234459
用Java列出某個文件目錄的文件列表是很容易實現的,只用調用File類中的list()方法即可。
代碼如下:
/此類實現Comparable接口
static class StringComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (returnDouble(s1) < returnDouble(s2))
return -1;
else if (returnDouble(s1) > returnDouble(s2))
return 1;
else
return 0;
}
}
public static double returnDouble(String str){
StringBuffer sb = new StringBuffer();
for(int i=0;i<str.length();i++){
if(Character.isDigit(str.charAt(i)))
sb.append(str.charAt(i));
else if(str.charAt(i)=='.'&&i<str.length()-1&&Character.isDigit(str.charAt(i+1)))
sb.append(str.charAt(i));
else break;
}
if(sb.toString().isEmpty())
return 0;
else
return Double.parseDouble(sb.toString());
}
由類StringComparator實現Comparator接口就可以改變String類型的默認排序方式,其中compare是需要復寫的方法,類似於Comparable接口中的compareTo方法。
returnDouble是寫的一個靜態方法,用來返回某個文件名字符串前面的數字編號,如"1.1.txt"返回的就是"1.1",寫的時候老是出現越界異常,后來終於改成功了,可能寫得有點復雜了。
這樣再調用Arrays類中的sort(T[] a, Comparator<? super T> c) 方法就可以對文件名排序了。
