标签:cto static blog yun string throws byte input net
原文地址: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) 方法就可以对文件名排序了。
标签:cto static blog yun string throws byte input net
原文地址:https://www.cnblogs.com/pijunqi/p/14265301.html