zoukankan      html  css  js  c++  java
  • java中替换文件内容

    package jbit.io;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class ReaderAndWriterFile {
    
    	 public void replaceFile(String file1,String file2) {   
    		   BufferedReader reader = null;
               BufferedWriter writer = null;
    		 try {
    			//创建 FileReader对象和FileWriter对象.
    			FileReader fr  = new FileReader(file1);  
    			FileWriter fw = new FileWriter(file2);
                //创建 输入、输入出流对象.
                reader = new BufferedReader(fr);
                writer = new BufferedWriter(fw);
                String line = null;
                StringBuffer sbf=new StringBuffer();  
                //循环读取并追加字符
                while ((line = reader.readLine()) != null) {
                    sbf.append(line);  
                }
                System.out.println("替换前:"+sbf);
                /*替换内容*/
                String newString=sbf.toString().replace("{name}", "欧欧");
                newString = newString.replace("{type}", "狗狗");
                newString = newString.replace("{master}", "李伟");
                System.out.println("替换后:"+newString);
                writer.write(newString);  //写入文件       
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
            	//关闭 reader 和 writer.
    			try {
    				if(reader!=null)
    					reader.close();
    				if(writer!=null)
    					writer.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	public static void main(String[] args) {
    		ReaderAndWriterFile obj = new ReaderAndWriterFile();
            obj.replaceFile("c:\pet.template", "D:\myDoc\pet.txt");          
    	}
    }
    

  • 相关阅读:
    JAVA 多线程开篇 -从按顺序打印ABC开始
    学英语
    称砝码
    JAVA BST的实现
    JAVA 引用
    常用查找算法的总结
    bootstrap学习之二-组件
    bootstrap学习之一_bootstrap css
    前端学习——css实用技术
    前端学习——css基础知识,选择器与html模板、值得收藏的html标签
  • 原文地址:https://www.cnblogs.com/a1111/p/12816617.html
Copyright © 2011-2022 走看看