首页 > 技术文章 > 修改文件,替换字符串

yangqimo 2017-10-20 18:29 原文

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>", "");  
    }  
}  

 

推荐阅读