如何使用 Java 將資料夾中的所有檔案讀入一個檔案中?
File 類的 listFiles() 方法返回一個數組,其中包含由當前(File)物件表示的路徑中的所有檔案(和目錄)的物件(抽象路徑)。
要將資料夾中所有檔案的內容讀入一個檔案中 -
- 透過將所需的檔案路徑作為引數傳遞來建立一個檔案物件。
- 使用 Scanner 或任何其他讀取器讀取每個檔案的內容。
- 將讀取的內容追加到 StringBuffer 中。
- 將 StringBuffer 內容寫入所需輸出檔案。
示例
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 {
//Creating a File object for directory
File directoryPath = new File("D:\SampleDirectory");
//List of all files and directories
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());
//Instantiating the Scanner class
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(" ");
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:\output.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.write(sb.toString().getBytes());
outputStream.flush();
System.out.println("Data entered into the file");
}
}
}輸出
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP