Java程式合併目錄中所有檔案的內容
在本文中,我們將學習如何使用 Java 將目錄中所有文字檔案的內容合併到一個檔案中。它讀取每個檔案的資料並將其寫入一個新檔案,同時確保所有資料都以組織的方式儲存。您將瞭解如何處理檔案、讀取其內容以及以程式設計方式合併它們。
File 類
java.io 包 包含 Java File 類,它提供了檔案和目錄路徑名的抽象表示。它通常用於建立檔案和目錄、搜尋檔案、刪除檔案以及執行其他與檔案相關的操作。
File my_file = new File(my_dir, file_name);
File 物件表示磁碟上的特定檔案或目錄。
BufferedReader 類
BufferedReader 類 旨在透過緩衝資料有效地從字元輸入流中讀取文字。它允許讀取字元、陣列或整行,使其成為處理大量文字資料同時最大程度減少 I/O 操作的理想選擇。這種緩衝機制提高了與直接從流中讀取相比的效能。
BufferedReader my_reader = new BufferedReader(new FileReader(my_file));
list() 方法:此方法用於獲取指定目錄 (my_dir) 內所有檔案的檔名。檔名儲存在 file_names 陣列中,稍後將對其進行迭代以讀取每個檔案的內容。
String[] file_names = my_dir.list();
PrintWriter 類
java.io.PrintWriter 類 用於將格式化文字寫入輸出流,支援字串、字元和其他資料型別。它還允許自動換行重新整理,以便於建立文字檔案。
我們將使用 PrintWriter 類中的 flush() 方法
my_writer.flush();
flush() 方法確保緩衝區中的所有資料都寫入檔案。
合併目錄中所有檔案的內容
以下是合併目錄中所有檔案內容的步驟:
- 設定檔案處理
建立一個 File 物件來表示包含我們將使用的文字檔案的目錄,File 類的 list() 方法獲取目錄中的所有檔名,並建立一個 PrintWriter 物件將合併後的內容寫入新檔案。 - 讀取和寫入檔案內容
使用 BufferedReader 一行一行讀取其內容,並使用 PrintWriter 將內容寫入新檔案。 - 完成
使用 PrintWriter 的 flush() 方法確保所有資料都寫入輸出檔案。
示例
要合併目錄中所有檔案的內容,Java 程式碼如下:
import java.io.*; // Importing classes for file handling public class Demo { public static void main(String[] args) throws IOException { // Specify the directory where files are located File my_dir = new File("path to place where file is generated"); // Create a PrintWriter to write the merged content into a new file PrintWriter my_writer = new PrintWriter("The .txt where changes are stored"); // Get a list of all file names in the specified directory String[] file_names = my_dir.list(); // Loop through each file name in the directory for (String file_name : file_names) { // Print the name of the file being read System.out.println("Content read from " + file_name); // Create a File object for the current file File my_file = new File(my_dir, file_name); // Create a BufferedReader to read the content of the file BufferedReader my_reader = new BufferedReader(new FileReader(my_file)); // Write the file name as a header in the output file my_writer.println("The file contains " + file_name); // Read the content of the file line by line String my_line = my_reader.readLine(); while (my_line != null) { // Write each line into the output file my_writer.println(my_line); // Read the next line my_line = my_reader.readLine(); } // Flush the writer to ensure all content is written my_writer.flush(); } // Print confirmation message after all files are merged System.out.println("All data from files have been read and merged into " + my_dir.getName()); } }
輸出
All file contents will be merged into a single text file.
廣告