以下为对文件的分割以及合并的操作
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import javax.swing.JOptionPane;
public class Split {
public static int Size = 1024;
public static void main(String[] args) throws IOException {
FileSplit("D:\\test\\xin.mp4"); //这里是要分割的文件的路径
//merge("D:\\test"); //这里是要将文件合并到的地方
}
public static void FileSplit(String path) throws IOException{
File file = new File(path);
if(file.exists()){
if(file.isFile()){
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = null;
int len = 0;
byte array[] = new byte[Size * 100]; //设置所分割的每个文件的大小
int count = 0;
while((len = fis.read(array))!=-1){
count++;
String newpath = file.getParent()+file.separator;
fos = new FileOutputStream(newpath + count + ".part"); //分割后的路径
fos.write(array,0,len);
}
fos.close();
fis.close();
JOptionPane.showMessageDialog(null, "分割成功!"); //分割成功后弹出对话框
}else{
System.out.println("传入的路径不是一个文件");
}
}
}
public static void merge(String path) throws IOException{
File file = new File(path);
if(file.exists()){
if(file.isDirectory()){
String str[] = file.list(); //将当前文件夹下的文件放到数组中
ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
for(String s:str){
if(s.endsWith(".part")){ //判断是否是以要合并的文件命名的
File f = new File(path+file.separator+s); //如果是,传入路径
list.add(new FileInputStream(f)); //加入到到list中
}
}
Enumeration<FileInputStream> e = Collections.enumeration(list); // 返回一个指定 collection 上的枚举。
SequenceInputStream seq = new SequenceInputStream(e); //后面用来读取文件
FileOutputStream fos = new FileOutputStream(path+file.separator+"new.mp4"); //合成后的位置
byte array[] = new byte[Size];
int len = 0;
while((len = seq.read(array))!=-1){
fos.write(array,0,len);
}
fos.close();
seq.close();
}
}
}
}
SequenceInputStream
表示其他输入流的逻辑串联。它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。
实现 Enumeration 接口的对象,它生成一系列元素,一次生成一个。连续调用 nextElement
方法将返回一系列的连续元素。
例如,要输出 Vector<E> v 的所有元素,可使用以下方法:
for (Enumeration<E> e = v.elements(); e.hasMoreElements();) System.out.println(e.nextElement());
这些方法主要通过向量的元素、哈希表的键以及哈希表中的值进行枚举。枚举也用于将输入流指定到 SequenceInputStream
中。
注:此接口的功能与 Iterator 接口的功能是重复的。此外,Iterator 接口添加了一个可选的移除操作,并使用较短的方法名。新的实现应该优先考虑使用 Iterator 接口而不是 Enumeration 接口。