Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

อ่านไฟล์ทั้งหมดในโฟลเดอร์รวมเป็นไฟล์เดียวใน Java

แนวทาง

  1. File.listFiles() ได้ Array ของไฟล์ทั้งหมด
  2. วนอ่านแต่ละไฟล์ด้วย Scanner (หรือ BufferedReader)
  3. สะสมเนื้อหาใน StringBuffer (Thread-safe) หรือ StringBuilder
  4. เขียน StringBuffer ลงไฟล์ Output ด้วย FileOutputStream / Files.write()

ตัวอย่างโค้ด

import java.io.*;

public class Test {
    public static void main(String args[]) throws IOException {
        File directoryPath = new File("D:\\SampleDirectory");
        File[] filesList = directoryPath.listFiles();

        StringBuffer sb = new StringBuffer();
        for (File file : filesList) {
            System.out.println("File: " + file.getName());
            try (Scanner sc = new Scanner(file)) {
                while (sc.hasNextLine()) {
                    sb.append(sc.nextLine()).append(" ");
                }
            }
        }

        // เขียนไฟล์ Output
        try (FileOutputStream fos = new FileOutputStream("D:\\output.txt");
             DataOutputStream dos = new DataOutputStream(fos)) {
            dos.write(sb.toString().getBytes());
            dos.flush();
            System.out.println("Data entered into the file");
        }
    }
}

ผลลัพธ์ตัวอย่าง

File: sample1.txt
File: sample2.txt
File: sample3.txt
Data entered into the file

เวอร์ชัน NIO.2 (สั้นกว่า)

import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

public class NioExample {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("D:\\SampleDirectory");
        Path output = Paths.get("D:\\output.txt");

        StringBuilder sb = new StringBuilder();
        try (Stream files = Files.list(dir)) {
            files.filter(Files::isRegularFile).forEach(f -> {
                try { Files.lines(f).forEach(line -> sb.append(line).append(" ")); }
                catch (IOException e) { throw new UncheckedIOException(e); }
            });
        }
        Files.write(output, sb.toString().getBytes());
        System.out.println("Merged into " + output);
    }
}

ข้อควรระวัง

  • Encoding: ใช้ StandardCharsets.UTF_8 ระบุชัดเจน
  • Large Files: ไม่ควรโหลดทั้งหมดใน Memory ใช้ Streaming เขียนทีละบรรทัด
  • Exception Handling: try-with-resources สำหรับ Resource Management