利用字符流复制文本文档,并且替换选中的特殊字符2

版权声明:原创内容是本人学习总结,仅限学习使用,禁止用于其他用途。如有错误和不足,欢迎评论指正补充。 https://blog.csdn.net/qian_qian_123/article/details/85238582
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();
			}
		}

	}
}

猜你喜欢

转载自blog.csdn.net/qian_qian_123/article/details/85238582
今日推荐