Java의 replaceAll() 메서드로 파일 내 문자열 삭제하기
replaceAll() 메서드는 정규 표현식(regular expression)과 문자열(String)을 매개변수로 받아, 현재 문자열의 내용이 주어진 정규 표현식과 일치할 경우 일치된 부분을 지정한 문자열로 대체합니다.
이 메서드를 활용하여 파일에서 특정 문자열을 삭제하려면 아래 세 가지 단계를 수행하면 됩니다.
- 파일의 전체 내용을 문자열(String) 형태로 읽어옵니다.
- replaceAll() 메서드를 사용하여 삭제하고 싶은 단어를 빈 문자열("")로 대체합니다.
- 대체가 완료된 결과 문자열을 다시 같은 파일에 덮어씁니다.
예제 코드
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StringExample {
public static String fileToString(String filePath) throws Exception{
String input = null;
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
return sb.toString();
}
public static void main(String args[]) throws FileNotFoundException {
String filePath = "D://sample.txt";
String result = fileToString(filePath);
System.out.println("파일 내용: "+result);
// 원하는 단어로 대체
result = result.replaceAll("\\bTutorialspoint\\b", "");
// 파일 내용 다시 쓰기
PrintWriter writer = new PrintWriter(new File(filePath));
writer.append(result);
writer.flush();
System.out.println("원하는 단어를 대체한 후의 파일 내용:");
System.out.println(fileToString(filePath));
}
}위 코드에서 fileToString() 메서드는 Scanner 클래스를 이용해 파일을 한 줄씩 읽고 StringBuffer에 누적한 뒤 하나의 문자열로 반환합니다. 그리고 PrintWriter 객체를 통해 수정된 문자열을 기존 파일에 덮어써서 변경 사항을 저장합니다.
실행 결과
파일 내용: Hello how are you welcome to Tutorialspoint 원하는 단어를 대체한 후의 파일 내용: Hello how are you welcome to
출력 결과를 보면 정규 표현식 \\bTutorialspoint\\b에 의해 'Tutorialspoint'라는 단어만 정확히 매칭되어 제거된 것을 확인할 수 있습니다. 여기서 \\b는 단어 경계(word boundary)를 의미하며, 이를 사용하면 다른 단어의 일부분까지 잘못 대체되는 것을 방지할 수 있습니다.