【0802作业】替换文本文件内容
1 package com.io; 2 /** 3 * 读取模板文件pet.template 4 * 将具体宠物信息存入,替换后保存成pet.txt 5 * 2019-08-04 6 * @author L 7 */ 8 import java.io.*; 9 10 public class Pet { 11 12 public static void main(String[] args) throws FileNotFoundException { 13 FileInputStream fis=null; 14 InputStreamReader isr=null; 15 BufferedReader br=null; 16 17 FileOutputStream fos=null; 18 OutputStreamWriter osw=null; 19 BufferedWriter bw=null; 20 21 try { 22 //读取 23 fis=new FileInputStream("D:\\pet.template"); 24 isr=new InputStreamReader(fis); 25 br=new BufferedReader(isr); 26 //写入 27 fos=new FileOutputStream("D:\\pet.txt"); 28 osw =new OutputStreamWriter(fos); 29 bw=new BufferedWriter(osw); 30 31 String str=""; 32 StringBuffer sbf=new StringBuffer(); 33 while((str=br.readLine())!=null){ 34 sbf.append(str); 35 } 36 System.out.print("替换前:"); 37 System.out.println(sbf.toString()); 38 39 40 String str2=sbf.toString(); 41 str2=str2.replace("{name}", "欧欧"); 42 str2=str2.replace("{type}", "狗狗"); 43 str2=str2.replace("{master}", "李伟"); 44 System.out.print("替换后:"); 45 System.out.println(str2); 46 bw.write(str2); 47 bw.flush(); 48 } catch (FileNotFoundException e) { 49 e.printStackTrace(); 50 } catch (IOException e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 }finally { 54 try { 55 bw.close(); 56 osw.close(); 57 fos.close(); 58 59 br.close(); 60 isr.close(); 61 fis.close(); 62 63 } catch (IOException e) { 64 // TODO Auto-generated catch block 65 e.printStackTrace(); 66 } 67 68 } 69 } 70 }