java替换txt文本中的字符串
public class TestDemo {
public static String read(File src) {
StringBuffer res = new StringBuffer();
String line = null;
try {
BufferedReader reader = new BufferedReader(new FileReader(src));
while ((line = reader.readLine()) != null) {
res.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res.toString();
}
public static boolean write(String cont, File dist) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(dist));
writer.write(cont);
writer.flush();
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public TestDemo() {
}
public static void main(String[] args) {
File src = new File("D:\\rili.log");
String cont = TestDemo.read(src);
System.out.println(cont);
// 对得到的内容进行处理
cont = cont.replaceAll("asd", "asdf");
System.out.println(cont);
// 更新源文件
System.out.println(TestDemo.write(cont, src));
}
}