读取文件并修改文件中特定字符串
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class FileChange {
public static void main(String[] args) {
File oldfile = new File("D:\\xxx\\xx.txt");
File newfile = new File("D:\\xxx\\xx.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(oldfile));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(newfile), "GBK");
String line = "";
String replace = "需要替换的字符串";
while ((line = br.readLine()) != null) {
if(!line.contains(replace))
osw.write(line+"\r\n");
}
br.close();
osw.close();
oldfile.delete();
newfile.renameTo(oldfile);
} catch (IOException e) {
e.printStackTrace();
}
}
}