public class BufferedTest {
public static void main(String[] args) {
/*
* 声明流对象
*/
FileReader fr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
FileWriter fw = null;
BufferedWriter bw = null;
try {
/*
* 1、读取模板文件内容
*/
fr = new FileReader("D:\\tools.template");
br = new BufferedReader(fr);
String str = br.readLine();
while (str != null) {
System.out.println(str);
sb.append(str);
str = br.readLine();
}
/*
* 2、替换读取的相关内容
*/
String newStr = sb.toString().replace("{name}", "欧欧").replace("{type}", "狗狗").replace("{master}", "李伟");
System.out.println("替换后:" + newStr);
/*
* 3、把生成的新内容,写入到指定的文件中
*/
File f = new File("D:/myDoc/pet.txt");
fw = new FileWriter(f);
bw = new BufferedWriter(fw);
bw.write(newStr);
System.out.println("write file scuessful!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*
* 4.关闭流对象
*/
try {
if (br != null) {
br.close();
}
if(fr != null){
fr.close();
}
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}