package teaching;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/**
* 按照规范格式保存宠物信息到HTML文件。
* @author 北大青鸟
*/
public class TestReaderWriter {
public static void main(String[] args) {
Reader fr = null;
Writer fw = null;
String path=System.getProperty("user.dir");
StringBuffer sb = new StringBuffer();
// 1、读取模板文件内容到StringBuffer
try {
fr = new FileReader(path+"");
char ch[] = new char[1024];
int length = 0;
length = fr.read(ch);
while (length != -1) {
sb.append(ch);
length = fr.read(ch);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fr)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 2、替换模板中占位符为具体内容
String str = sb.toString();
str = str.replace("{name}", "欧欧");
str = str.replace("{type}", "狗狗");
str = str.replace("{master}", "李伟");
// 3、输出替换后内容到HTML文件
try {
fw = new FileWriter("d:\\pet.html");
fw.write(str.trim());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fw)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}