//定义模板文件路径
private static final String TMPL_FILE_NAME = "data/data.tml";
/*
字符流输入流:以Reader作为父类 具体类:FileReader 和 Buffered Reader ---- 读取数据
字符输出流:以Writer作为父类 具体类:FileWriter 和 BufferedWriter ---- 写入数据
*/
public static StringBuffer readFromFile(File srcFile){
//try-witch-resource语法糖 try(释放资源对象) {} catch(Exception e)
StringBuffer sb = new StringBuffer(16);
try (
var reader = new BufferedReader(new FileReader(srcFile),8192);
){
String line = "";
//使用循环每次读取一行,将读取到每一行数据追加到字符串容量中
while ((line = reader.readLine()) != null){
sb.append(line).append("\r\t");
}
return sb;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 处理数据,将占位符替换成真实数据
* @param buffer 字符串数据
* @return 返回替换后的真实数据
*/
public static String processData(StringBuffer buffer){
return buffer.toString()
.replace("{name}","欧欧")
.replace("{type}","拉布拉多")
.replace("{master}","李伟");
}
//将处理后的新数据写入到目标文件中
public static boolean writeToFile(String content,File targetFile){
try (
//创建写入器对象
var writer = new BufferedWriter(new FileWriter(targetFile));
){
writer.write(content);
//强制刷新缓冲区
writer.flush();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
StringBuffer buffer = readFromFile(new File(TMPL_FILE_NAME));
String content = processData(buffer);
boolean result = writeToFile(content,new File("data/pet.txt"));
System.out.println(result ? "写入成功" : "写入失败");
}
替换前:
替换后
那么我们的文件目录就会有一个pet.txt 替换后的新文件