方法一:多个文件的输出流流入目标文件
* 作用:
*
*@author hby_gd@163.com
*@date 3/6/2020 下午4:11
*/
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class MergeFIle {
private String endFilePath;
private File endFile;
private List<String> fileList=null;
public MergeFIle() {}
public MergeFIle(String endFilePath) {
if(isRight(endFilePath)){
endFile = new File(endFilePath);
fileList=new ArrayList<String>();
}
}
//判断文件路径是否合法
private boolean isRight(String path){
if(null==path||new File(path).isDirectory()){
System.out.println("目标文件路径有误");
return false;
}
return true;
}
//方法入口
public void merge(){
for(String filepath:fileList){
File file = new File(filepath);
mergeDetail(filepath);
}
}
//文件插入列表
public boolean addFile(String fileName){
if (isRight(fileName)){
fileList.add(fileName);
return true;
}else {
System.out.println("文件路径有误");
return false;
}
}
//插入单个文件
private void mergeDetail(String filePath){
File file = new File(filePath);
try (
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(new FileOutputStream(endFile,true));
){
byte[] flush = new byte[1024];
int len =0;
while(-1!=(len=in.read(flush))){
out.write(flush,0,len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法二:多个文件的输入流流入汇总流,汇总流流出至目标文件 SequenceInputStream
SequenceInputStream(Enumeration<? extends InputStream> e),
构造方法需要枚举类型的输入流
Enumeration枚举类型可以由 Vector.elements()方法得到,所以要构建一个InputStream泛型Vector
public void merge2() throws FileNotFoundException {
Vector<InputStream> fileVector = new Vector<>();
for(String filepath:fileList){
File file = new File(filepath);
InputStream i = new BufferedInputStream(new FileInputStream(file));
fileVector.add(i);
}
SequenceInputStream sqis = new SequenceInputStream(fileVector.elements());
try (
InputStream in = sqis;
OutputStream out = new BufferedOutputStream(new FileOutputStream(endFile,true));
){
byte[] flush = new byte[1024];
int len =0;
while(-1!=(len=in.read(flush))){
out.write(flush,0,len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}