--- /dev/null
+/*
+ * Meviz - Various tools collection to work with multimedia.
+ * Copyright (C) 2012, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of version 2 of the GNU General Public License
+ * as published by the Free Software Foundation.
+ */
+
+package eu.svjatoslav.meviz.replace;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import eu.svjatoslav.meviz.Module;
+
+public class Main implements Module {
+
+ CommandlineHandler commandlineHandler = new CommandlineHandler();
+
+ CommandlineOptions options;
+
+
+ @Override
+ public String getDescription() {
+ return "Replace one string to another string in all occurrances and all files recursively.";
+ }
+
+ @Override
+ public String getModuleCommand() {
+ return "replace";
+ }
+
+ public void processDirectory(final File directory) {
+
+ for (final File file : directory.listFiles())
+ if (file.isDirectory()) {
+ if (options.recursive)
+ processDirectory(file);
+ } else
+ try {
+ processFile(file);
+ } catch (final IOException exception) {
+ System.out.println("Error processing file: "
+ + file.getAbsolutePath());
+ System.out.println(" exception: "
+ + exception.getMessage());
+ }
+
+ }
+
+ public void processFile(final File file) throws IOException {
+
+ FileReader fileReader = new FileReader(file);
+ BufferedReader bufferedReader = new BufferedReader(fileReader);
+
+ StringBuffer result = new StringBuffer();
+
+ boolean contentChanged = false;
+
+ while (true) {
+ String line = bufferedReader.readLine();
+ if (line == null)
+ break;
+
+ String newLine = line.replace(options.searchForPattern,
+ options.replaceWithPattern);
+
+ if (!contentChanged)
+ if (!newLine.equals(line))
+ contentChanged = true;
+
+ result.append(newLine);
+ result.append("\n");
+ }
+
+ bufferedReader.close();
+ fileReader.close();
+
+ if (contentChanged) {
+ FileWriter fileWriter = new FileWriter(file);
+ fileWriter.write(result.toString());
+ fileWriter.close();
+ }
+
+ }
+
+ @Override
+ public void run(final String[] args) throws IOException {
+
+ options = commandlineHandler.parseCommandlineArguments(args);
+
+ if (options == null) {
+ showCommandlineHelp();
+ return;
+ }
+
+ processDirectory(options.targetDirectory);
+
+ }
+
+ @Override
+ public void showCommandlineHelp() {
+ commandlineHandler.initParser().showHelp();
+ }
+
+}