天天看點

IO流合并檔案

多個檔案合并成一個(FileInputStream)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

public class Test {
    public static void main(String params[]) throws Exception {
        String[] iF = new String[] {"E:/test1.txt", "E:/test2.txt", "E:/test3.txt", "E:/test4.txt" };
        String oF = "E:/out.txt";
        FileOutputStream output = new FileOutputStream(new File(oF));
        WritableByteChannel targetChannel = output.getChannel();
        for(int i =0; i<iF.length; i++){
            FileInputStream input = new FileInputStream(iF[i]);
            FileChannel inputChannel = input.getChannel();
            inputChannel.transferTo(0, inputChannel.size(), targetChannel);
            inputChannel.close();
            input.close();
        }
        targetChannel.close();
        output.close();
        System.out.println("All jobs done...");
    }
}
           

使用BufferedInputStream

import java.io.*;

public class CombineFiles {
    /**
     * 遞歸周遊檔案,查找符合字尾名文檔案讀入
     * @param file
     */
    public static void recursiveTraversalFiles(File file,BufferedOutputStream bos) throws IOException {
        if(file.isFile()){
            //擷取檔案名
            String fileName = file.getName();
            //截取字尾名
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            if("md".equals(suffix)){
                //判斷是md檔案,完成檔案讀入操作
                System.out.println(fileName);
                readFile(file,bos);
            }
        }else {
            File[] files = file.listFiles();
            for(File fi :files){
                //遞歸周遊檔案
               recursiveTraversalFiles(fi,bos);
            }
        }
    }

    /**
     * 檔案讀入操作
     * @param file
     * @param bos
     */
    public static void readFile(File file,BufferedOutputStream bos){
        BufferedInputStream bis = null;;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int len =-1;
            byte[] bytes = new byte[1024];
            while((len = bis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
         //需要遞歸周遊的檔案夾的絕對路徑
        File file = new File("F:\\MyFiles\\Test");
        //合并之後的檔案的路徑以及檔案名
        File outFile = new File("F:\\MyFiles\\Test\combineFile.md");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
        recursiveTraversalFiles(file,bos);
        bos.close();
    }

}
           

第二種合并方式使用BufferedWriter

import java.io.*;
import java.util.*;

public class MergeFilesToOne {
    public static void main(String[] args) throws IOException {
        String in = "F:/AAA";
        String out = "F:/BBB/success.txt";
        // 合并
        mergeFileToOne(in, out);
    }

    /**
     * 遞歸擷取檔案夾以及子檔案夾下的檔案
     *
     * @param path
     * @return
     */
    public static List getFiles(String path) {
        List list = new ArrayList();
        File[] files = new File(path).listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                List node = getFiles(files[i].getPath());
                list.addAll(node);
            } else {
                list.add(files[i].getPath());
            }
        }
        return list;
    }

    /**
     * 合并檔案
     *
     * @param inPath
     * @param outPath
     * @throws IOException
     */
    public static void mergeFileToOne(String inPath, String outPath) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(outPath));
        System.out.println("--->合并目标檔案夾路徑:" + inPath);
        System.out.println("--->正在讀取檔案...");
        List<String> files = getFiles(inPath);
        System.out.println("--->合并檔案數量:" + files.size());
        for (int i = 0; i < files.size(); i++) {
            File file = new File(files.get(i));
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            bufferedReader.close();
        }
        System.out.println("--->合并完成!");
        System.out.println("--->合并檔案輸出路徑:" + outPath);
        bw.close();
    }
}