pet.template
您好!
我的名字是{name},我是一只{type}。
我的主人是{master}。
复制替换成如下:
pet.txt
您好!
我的名字是丫丫,我是一只企鹅。
我的主人是小明。
代码如下:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 通过字符流复制文本文档,
*
* 实际是利用string作为假设的缓冲
*
* @author zhangwendi
*
*/
public class DD {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("d:/pet.template");
fw = new FileWriter("d:/pet.txt");
// 可以把read()读到的数据,拼接成String,类似于缓冲流
String str = "";
// StringBuffer
int content = -1;
while ((content = fr.read()) != -1) {
char ch = (char) content;
System.out.print(ch);
str = str + ch;
}
// String 的replace("需要替换的内容","替换成的什么")
str = str.replace("{name}", "丫丫");
str = str.replace("{type}", "企鹅");
str = str.replace("{master}", "小明");
System.out.println("\n" + str);
// 通过字符流将数据写到文本文档
fw.write(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}