Replace file

private static final String ENTER = "\r\n";
    public void replaceByDirectory(File rootFile, String oldValue, String newValue) {
        if (rootFile.isFile()) {
            if (checkFile(rootFile.getName())) {
                replaceFile(rootFile, oldValue, newValue);
            }
        } else if (rootFile.isDirectory()) {
            File [] files = rootFile.listFiles();
            for (File file : files) {
                replaceByDirectory(file, oldValue, newValue);
            }
        }
    }
    
    private void replaceFile(File file, String oldValue, String newValue) {
        if (file.exists()) {
            boolean isFound = false;
            List<String> content = this.readFile(file);
            List<String> result = new ArrayList<String>();
            for (String line : content) {
                if (line.indexOf(oldValue) >= 0) {
                    result.add(line.replace(oldValue, newValue));
                    isFound = true;
                } else {
                    result.add(line);
                }
            }
            
            if (isFound) {
                System.out.println(file.getName());
                this.writeFile(result, file);
            }
        }
    }
    
    private List<String> readFile(File file) {
        List<String> content = new ArrayList<String>();
        if (file != null && file.isFile()) {
            String line = null;
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                while ((line = reader.readLine()) != null) {
                    content.add(line);
                }
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return content;
    }
    
    private void writeFile(List<String> content, File file) {
        if (file != null && file.isFile()) {
            BufferedWriter writer;
            try {
                writer = new BufferedWriter(new FileWriter(file));
                for (String line : content) {
                    writer.write(line);
                    writer.write(ENTER);
                }
                
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(replace)