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

Đọc tất cả file trong thư mục gộp vào một file duy nhất trong Java

Phương thức listFiles() của lớp File trả về mảng object (đường dẫn trừu tượng) của tất cả file và thư mục trong path của object File hiện tại.

Để đọc nội dung tất cả file trong folder vào một file duy nhất:

  • Tạo File object với đường dẫn thư mục
  • Đọc nội dung từng file bằng Scanner hoặc reader khác
  • Append nội dung đọc được vào StringBuffer
  • Ghi nội dung StringBuffer vào file output yêu cầu

Ví dụ

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Test {
    public static void main(String args[]) throws IOException {
        File directoryPath = new File("D:\\SampleDirectory");
        File filesList[] = directoryPath.listFiles();
        System.out.println("List of files and directories in the specified directory:");
        
        Scanner sc = null;
        StringBuffer sb = new StringBuffer();
        
        for (File file : filesList) {
            System.out.println("File name: " + file.getName());
            System.out.println("File path: " + file.getAbsolutePath());
            System.out.println("Size: " + file.getTotalSpace());
            
            sc = new Scanner(file);
            String input;
            while (sc.hasNextLine()) {
                input = sc.nextLine();
                sb.append(input + " ");
            }
            System.out.println("Contents of the file: " + sb.toString());
            System.out.println(" ");
            
            FileOutputStream fileOut = new FileOutputStream("D:\\output.txt");
            DataOutputStream outputStream = new DataOutputStream(fileOut);
            outputStream.write(sb.toString().getBytes());
            outputStream.flush();
            System.out.println("Data entered into the file");
        }
    }
}

Đầu ra

List of files and directories in the specified directory:
File name: sample1.txt
File path: D:\SampleDirectory\sample1.txt
Contents of the file: sample text file1
Data entered into the file
File name: sample2.txt
File path: D:\SampleDirectory\sample2.txt
Contents of the file: sample text file2
Data entered into the file
File name: sample3.txt
File path: D:\SampleDirectory\sample3.txt
Contents of the file: sample text file3
Data entered into the file