1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.UnsupportedEncodingException; 9 10 public class ReaderAndWriterDome01 { 11 public static void main(String[] args) { 12 String str = "C:\\Users\\Administrator\\Desktop\\模板文件-上机素材\\pet.template"; 13 String str1 = "C:\\Users\\Administrator\\Desktop\\模板文件-上机素材\\01.txt"; 14 BufferedReader reader = null; 15 InputStreamReader isr = null; 16 FileInputStream fis = null; 17 BufferedWriter writer = null; 18 FileWriter fw = null; 19 try { 20 fis = new FileInputStream(str); 21 isr = new InputStreamReader(fis,"UTF-8"); 22 reader = new BufferedReader(isr); 23 24 fw = new FileWriter(str1); 25 writer = new BufferedWriter(fw); 26 StringBuffer sbf = new StringBuffer(); 27 String line = null; 28 while((line = reader.readLine()) != null) { 29 sbf.append(line); 30 } 31 System.out.println("替换成的文本内容:"); 32 System.out.println(sbf); 33 34 String NewString = sbf.toString().replace("{name}", "欧欧"); 35 NewString = NewString.replace("{type}", "狗狗"); 36 NewString = NewString.replace("{master}", "李伟"); 37 System.out.println("替换后的文本内容:"); 38 System.out.println(NewString); 39 writer.write(NewString); 40 writer.flush(); 41 } catch (FileNotFoundException e) { 42 e.printStackTrace(); 43 } catch (UnsupportedEncodingException e) { 44 e.printStackTrace(); 45 } catch (IOException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 }finally{ 49 try { 50 if(reader!=null) 51 reader.close(); 52 if(writer!=null) 53 writer.close(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 } 59 }文本内容替换