java文件替換寫法
阿新 • • 發佈:2018-11-14
write new system mon stack () trace close nts
@Test
public void we1() throws Exception {
FileReader fileReader = new FileReader("a.txt");
FileWriter fileWriter = new FileWriter("ss.txt");
File src = new File("H:/test.txt");
String cont = Monitoring.readfileconten("H:/test.txt");
System.out.println(cont);
//對得到的內容進行處理
cont = cont.replaceAll("aaa", "bbb");
System.out.println(cont);
//更新源文件
System.out.println(Monitoring.write(cont, src));
}
public static String readfileconten(String path) {
File file = new File(path);
StringBuffer stringBuffer = new StringBuffer();
String lin = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
while ((lin = bufferedReader.readLine()) != null) {
stringBuffer.append(lin + "\n");
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.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;
}
}
java文件替換寫法