2 * Meviz - Various tools collection to work with multimedia. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
7 package eu.svjatoslav.meviz.replace;
9 import eu.svjatoslav.meviz.Module;
13 public class Main implements Module {
15 private final CommandlineHandler commandlineHandler = new CommandlineHandler();
17 private CommandlineOptions options;
20 public String getDescription() {
21 return "Replace one string to another string in all occurrances and all files recursively.";
25 public String getModuleCommand() {
29 private void processDirectory(final File directory) {
31 for (final File file : directory.listFiles())
32 if (file.isDirectory()) {
33 if (options.recursive)
34 processDirectory(file);
38 } catch (final IOException exception) {
39 System.out.println("Error processing file: "
40 + file.getAbsolutePath());
41 System.out.println(" exception: "
42 + exception.getMessage());
47 private void processFile(final File file) throws IOException {
49 final FileReader fileReader = new FileReader(file);
50 final BufferedReader bufferedReader = new BufferedReader(fileReader);
52 final StringBuilder result = new StringBuilder();
54 boolean contentChanged = false;
57 final String line = bufferedReader.readLine();
61 final String newLine = line.replace(options.searchForPattern,
62 options.replaceWithPattern);
65 if (!newLine.equals(line))
66 contentChanged = true;
68 result.append(newLine);
72 bufferedReader.close();
76 final FileWriter fileWriter = new FileWriter(file);
77 fileWriter.write(result.toString());
84 public void run(final String[] args) throws IOException {
86 options = commandlineHandler.parseCommandlineArguments(args);
88 if (options == null) {
89 showCommandlineHelp();
93 processDirectory(options.targetDirectory);
98 public void showCommandlineHelp() {
99 commandlineHandler.parser.showHelp();