1 package com.twod3z; 2 3 import java.io.*; 4 5 /** 6 * @program: com.twod3z 7 * @description:替换文本文件内容 8 * @author: Mr.Lin 9 * @create: 2019年8月3日 10 **/ 11 public class ReaderAndWriterDemo { 12 public static void main(String[] args) { 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:/mydoc/pet.template"); 24 isr = new InputStreamReader(fis); 25 br = new BufferedReader(isr); 26 27 fos = new FileOutputStream("d:/mydoc/newpet"); 28 osw = new OutputStreamWriter(fos); 29 bw = new BufferedWriter(osw); 30 31 String s= ""; 32 String s2 = ""; 33 System.out.print("替换前:"); 34 while( (s = br.readLine())!=null ) { 35 System.out.print(s); 36 s2+=s; 37 } 38 39 s2 = s2.replace("{name}", "小黑"); 40 s2 = s2.replace("{type}", "狗狗"); 41 s2 = s2.replace("{master}", "李伟"); 42 System.out.println(" 替换后:"+s2); 43 44 bw.write(s2); 45 46 } catch (FileNotFoundException e) { 47 // TODO Auto-generated catch block 48 e.printStackTrace(); 49 } catch (IOException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } finally { 53 try { 54 bw.close(); 55 osw.close(); 56 fos.close(); 57 br.close(); 58 isr.close(); 59 fis.close(); 60 } catch (IOException e) { 61 // TODO Auto-generated catch block 62 e.printStackTrace(); 63 } 64 65 } 66 67 } 68 }