여러 개의 텍스트 파일에 흩어져 있는 내용을 하나의 파일로 합쳐야 하는 경우가 종종 있습니다. 이 글에서는 Java의 Scanner와 FileWriter 클래스를 활용하여 두 개 이상의 파일을 한 줄씩 번갈아 읽어 세 번째 파일에 병합하는 방법을 소개합니다.
예제 입력 파일
설명을 위해 다음과 같이 세 개의 파일이 준비되어 있다고 가정하겠습니다.
output1.txt
Hello how are you
output2.txt
Welcome to Tutorialspoint
output3.txt
We provide simply easy learning
예제 코드
아래 예제는 세 파일의 내용을 한 줄씩 번갈아 읽어 result.txt라는 단일 파일에 순서대로 기록합니다.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MergingFiles {
public static void main(String args[]) throws IOException {
Scanner sc1 = new Scanner(new File("D://input1.txt"));
Scanner sc2 = new Scanner(new File("D://input2.txt"));
Scanner sc3 = new Scanner(new File("D://input3.txt"));
FileWriter writer = new FileWriter("D://result.txt");
// 세 파일을 번갈아 가며 한 줄씩 읽어 결과 파일에 추가
while (sc1.hasNextLine() || sc2.hasNextLine() || sc3.hasNextLine()) {
if (sc1.hasNextLine()) {
writer.append(sc1.nextLine() + "\n");
}
if (sc2.hasNextLine()) {
writer.append(sc2.nextLine() + "\n");
}
if (sc3.hasNextLine()) {
writer.append(sc3.nextLine() + "\n");
}
}
writer.flush();
writer.close();
System.out.println("Contents added");
}
}
실행 결과
Contents added
코드 설명
- Scanner 객체 생성: 각 입력 파일을 읽기 위해 파일별로 Scanner 객체를 생성합니다.
- FileWriter: 병합된 내용을 저장할 출력 파일(result.txt)을 엽니다.
- hasNextLine() 검사: while 조건에서 세 파일 중 하나라도 읽을 줄이 남아 있는지 확인하고, if 문으로 줄이 남아 있는 파일만 골라 기록합니다. 덕분에 파일마다 줄 수가 달라도 오류 없이 병합할 수 있습니다.
- flush()와 close(): 버퍼에 남은 데이터를 모두 디스크에 기록한 뒤 자원을 해제합니다.
병합이 완료된 result.txt 파일을 열어 보면 세 파일의 내용이 아래와 같이 순서대로 저장되어 있습니다.
Hello how are you Welcome to Tutorialspoint We provide simply easy learning
응용: 디렉터리의 모든 파일을 하나로 합치기
병합할 파일들이 같은 디렉터리에 모여 있다면 파일 이름을 일일이 지정하지 않아도 됩니다. listFiles() 메서드로 디렉터리 내 모든 파일을 가져온 뒤, 반복문으로 각 파일의 내용을 하나의 출력 파일에 차례대로 이어 붙이면 됩니다.
예제 코드
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MergingFiles {
public static void main(String args[]) throws IOException {
// 디렉터리를 나타내는 File 객체 생성
File directoryPath = new File("D:\\example");
// 디렉터리 안의 모든 파일 목록 가져오기
File filesList[] = directoryPath.listFiles();
FileWriter writer = new FileWriter("D://output.txt");
for (File file : filesList) {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String input = sc.nextLine();
writer.append(input + "\n");
}
sc.close();
}
writer.flush();
writer.close();
System.out.println("Contents added");
}
}
실행 결과
Contents added
마무리
이처럼 Scanner와 FileWriter만 있으면 별도의 외부 라이브러리 없이도 여러 파일을 손쉽게 하나로 병합할 수 있습니다. 실무에서 파일 개수가 많거나 대용량 데이터를 다룰 때는 try-with-resources 구문을 함께 사용해 자원 누수를 방지하는 것이 좋습니다.