码迷,mamicode.com
首页 > 其他好文 > 详细

修改文件,替换字符串

时间:2017-10-20 20:18:37      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:bre   pat   pfile   int   运行   div   filename   tabs   重命名   

public class Modify {  
  
    private String path;  
    private final String target;  
    private final String newContent;  
  
    public Modify(String path, String target, String newContent) {  
        // 操作目录。从该目录开始。该文件目录下及其所有子目录的文件都将被替换。  
        this.path = path;  
        // target:需要被替换、改写的内容。  
        this.target = target;  
        // newContent:需要新写入的内容。  
        this.newContent = newContent;  
  
        operation();  
    }  
  
    private void operation() {  
        File file = new File(path);  
        opeationDirectory(file);  
    }  
  
    public void opeationDirectory(File dir) {  
  
        File[] files = dir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            File f = files[i];  
            if (f.isDirectory())  
                // 如果是目录,则递归。  
                opeationDirectory(f);  
            if (f.isFile())  
                operationFile(f);  
        }  
    }  
  
    public void operationFile(File file) {  
  
        try {  
            InputStream is = new FileInputStream(file);  
            BufferedReader reader = new BufferedReader(  
                    new InputStreamReader(is));  
  
            String filename = file.getName();  
            // tmpfile为缓存文件,代码运行完毕后此文件将重命名为源文件名字。  
            File tmpfile = new File(file.getParentFile().getAbsolutePath()  
                    + "\\" + filename + ".tmp");  
  
//            BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));  
            PrintWriter writer = new PrintWriter(new FileWriter(tmpfile));  
  
            boolean flag = false;  
            String str = null;  
            while (true) {  
                str = reader.readLine();  
  
                if (str == null)  
                    break;  
  
                if (str.contains(target)) { 
                    writer.write(str.replace(target, newContent)+"\r\n");  
                    flag = true;  
                } else  
                    writer.write(str+"\r\n");
            }  
  
            is.close();  
  
            writer.flush();  
            writer.close();  
  
            if (flag) {  
                file.delete();  
                tmpfile.renameTo(new File(file.getAbsolutePath()));  
            } else  
                tmpfile.delete();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static void main(String[] args) {  
        //代码测试:假设有一个test文件夹,test文件夹下含有若干文件或者若干子目录,子目录下可能也含有若干文件或者若干子目录(意味着可以递归操作)。        
        new Modify("c:\\zz", "</p>", "");  
    }  
}  

 

修改文件,替换字符串

标签:bre   pat   pfile   int   运行   div   filename   tabs   重命名   

原文地址:http://www.cnblogs.com/yangqimo/p/7700974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!