替换文本内容(IO流)

 

代码

package com.I_O;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class Pet_replace {
    public static void main(String[] args) {
        Reader r=null;
        BufferedReader br=null;
        Writer w=null;
        BufferedWriter bw=null;
        
        try {
            r=new InputStreamReader(new FileInputStream("E:\\javaFile\\Pet/P.txt"));
            br=new BufferedReader(r);
            w=new OutputStreamWriter(new FileOutputStream("E:\\javaFile\\Pet/pet.txt"));
            bw=new BufferedWriter(w);
            
            String s="";                            //读取的一行
            StringBuffer sbf=new StringBuffer();    //总共读取的集合
            
            while((s=br.readLine())!=null) {        //读取每一行
                sbf=sbf.append(s);                    //添加读取的每一行
            }
            System.out.println("替换前:"+sbf);
            s=sbf.toString();                        //StringBuffer转成String
            String newString=s.replace("name", "可乐").replace("animal", "猫 ").replace("age", "2");
            System.out.println("替换后:"+newString);
            bw.write(newString);                    //写入文档
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
                w.close();
                br.close();
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

 

运行

 

posted @ 2019-03-08 20:14  纸灰  阅读(300)  评论(0编辑  收藏  举报