Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Gộp nhiều file luân phiên vào file mới – Java

Đọc từng dòng từ nhiều file, ghi luân phiên (dòng 1 file A, dòng 1 file B, dòng 1 file C, dòng 2 file A...).

Ví dụ: Gộp 3 file cố định


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

public class MergeFilesAlternating {
    public static void main(String[] args) throws IOException {
        File f1 = new File("D:/input1.txt");
        File f2 = new File("D:/input2.txt");
        File f3 = new File("D:/input3.txt");
        File out = new File("D:/merged.txt");
        
        try (Scanner s1 = new Scanner(f1);
             Scanner s2 = new Scanner(f2);
             Scanner s3 = new Scanner(f3);
             PrintWriter pw = new PrintWriter(new FileWriter(out))) {
            
            while (s1.hasNextLine() || s2.hasNextLine() || s3.hasNextLine()) {
                if (s1.hasNextLine()) pw.println(s1.nextLine());
                if (s2.hasNextLine()) pw.println(s2.nextLine());
                if (s3.hasNextLine()) pw.println(s3.nextLine());
            }
        }
        System.out.println("Đã gộp xong: " + out.getAbsolutePath());
    }
}

Input files


// input1.txt
Dòng 1 - File 1
Dòng 2 - File 1

// input2.txt
Dòng 1 - File 2

// input3.txt
Dòng 1 - File 3
Dòng 2 - File 3
Dòng 3 - File 3

Output merged.txt


Dòng 1 - File 1
Dòng 1 - File 2
Dòng 1 - File 3
Dòng 2 - File 1
Dòng 2 - File 3
Dòng 3 - File 3

Mở rộng: Gộp tất cả file trong thư mục


File dir = new File("D:/input_folder");
File[] files = dir.listFiles((d, name) -> name.endsWith(".txt"));

try (PrintWriter pw = new PrintWriter(new FileWriter("D:/merged_all.txt"))) {
    boolean any;
    do {
        any = false;
        for (File f : files) {
            try (Scanner sc = new Scanner(f)) {
                if (sc.hasNextLine()) {
                    pw.println(sc.nextLine());
                    any = true;
                }
            }
        }
    } while (any);
}

⚠️ Lưu ý

  • Mở/đóng Scanner cho mỗi file trong vòng lặp → chậm nếu nhiều file/lặp nhiều lần
  • Tối ưu: Mở tất cả Scanner trước, lưu vào List, sau đó vòng lặp đọc
  • Encoding: Dùng new Scanner(file, "UTF-8") và new OutputStreamWriter(new FileOutputStream(out), "UTF-8")