Java IO流文件合并

方法一:多个文件的输出流流入目标文件

 * 作用:
 *
 *@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();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值