
步骤:
- 1、先从文件中读取所有内容
- 2、字符串替换{}
- 3、写入文件
代码:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//1、先从文件中读取所有内容
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader("e:\\Pet.template");
fw=new FileWriter("e:\\Pet.template");
char[] aryChar=new char[1024];
fr.read(aryChar);
String str=String.valueOf(aryChar);
System.out.println(str);
//2、字符串替换{}
System.out.println("昵称");
String name=input.next();
System.out.println("年龄:");
String age=input.next();
System.out.println("主人:");
String master=input.next();
String newStr1=str.replace("{name}", name);
String newStr2=newStr1.replace("{age}", age);
String newStr3=newStr2.replace("{master}", master);
System.out.println(newStr3);
//3、写入文件
fw.write(newStr3);
fw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}