replaceAll() 메소드는 정규식과 문자열을 매개변수로 받아들이고 현재 문자열의 내용을 주어진 정규식과 일치시키고 일치하는 경우 일치하는 요소를 문자열로 대체합니다.
replaceAll() 메서드를 사용하여 파일에서 특정 문자열을 삭제하려면 -
-
파일의 내용을 문자열로 검색합니다.
-
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("Contents of the file: "+result);
//Replacing the word with desired one
result = result.replaceAll("\\bTutorialspoint\\b", "");
//Rewriting the contents of the file
PrintWriter writer = new PrintWriter(new File(filePath));
writer.append(result);
writer.flush();
System.out.println("Contents of the file after replacing the desired word:");
System.out.println(fileToString(filePath));
}
} 출력
Contents of the file: Hello how are you welcome to Tutorialspoint Contents of the file after replacing the desired word: Hello how are you welcome to