listFiles() 파일 메서드 클래스는 현재(파일) 개체가 나타내는 경로에 있는 모든 파일(및 디렉터리)의 개체(추상 경로)를 포함하는 배열을 반환합니다.
폴더에 있는 모든 파일의 내용을 단일 파일로 읽으려면 -
- 필수 파일 경로를 매개변수로 전달하여 파일 객체를 생성합니다.
- 스캐너 또는 기타 리더를 사용하여 각 파일의 내용을 읽습니다.
- 읽은 내용을 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