|
| 1 | +package ch_18.exercise18_31; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.List; |
| 5 | +import java.util.stream.Collectors; |
| 6 | + |
| 7 | +/** |
| 8 | + * 18.31 (Replace words) Write a program that replaces all occurrences of a word with a |
| 9 | + * new word in all the files under a directory, recursively. Pass the parameters from |
| 10 | + * the command line as follows: |
| 11 | + * <p> |
| 12 | + * java Exercise18_31 dirName oldWord newWord |
| 13 | + * <p> |
| 14 | + * Example cmd: |
| 15 | + * javac Exercise18_31.java |
| 16 | + * java Exercise18_31 ch_18/exercise18_31/TestDirectory the bologna |
| 17 | + */ |
| 18 | +public class Exercise18_31 { |
| 19 | + public static void main(String[] args) { |
| 20 | + if (args.length < 2) { |
| 21 | + System.err.println("Usage: java Exercise18_30 dirName word"); |
| 22 | + System.exit(0); |
| 23 | + } |
| 24 | + |
| 25 | + String directory = args[0]; |
| 26 | + String oldWord = args[1]; |
| 27 | + String newWord = args[2]; |
| 28 | + |
| 29 | + File dir = new File(directory); |
| 30 | + |
| 31 | + if (dir.isDirectory()) { |
| 32 | + File[] files = dir.listFiles(); |
| 33 | + if (files != null && files.length > 0) { |
| 34 | + try { |
| 35 | + replaceWords(files, oldWord, newWord, 0); |
| 36 | + } catch (IOException ioException) { |
| 37 | + ioException.printStackTrace(); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + } else { |
| 42 | + System.out.println("Please specify a Directory for 'dirName'. "); |
| 43 | + } |
| 44 | + System.out.println("The word: \"" + oldWord + "\" has been replaced with \"" + newWord + "\" for files in " + |
| 45 | + "directory: " + dir.getName()); |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + static void replaceWords(File[] files, String oldWord, String newWord, int fileIndex) throws IOException { |
| 50 | + if (files.length == fileIndex) { |
| 51 | + return; |
| 52 | + } |
| 53 | + runReplace(oldWord, newWord, files[fileIndex]); |
| 54 | + replaceWords(files, oldWord, newWord, fileIndex + 1); // Recurse |
| 55 | + } |
| 56 | + |
| 57 | + /* Method to perform replacement logic */ |
| 58 | + static void runReplace(String oldWord, String newWord, File file) throws IOException { |
| 59 | + if (file.isFile()) { |
| 60 | + FileReader fileReader = new FileReader(file); |
| 61 | + BufferedReader bufferedReader = new BufferedReader(fileReader); |
| 62 | + List<String> resultList = bufferedReader.lines() |
| 63 | + .map(s -> s.replace(oldWord, newWord)) |
| 64 | + .collect(Collectors.toList()); |
| 65 | + |
| 66 | + bufferedReader.close(); |
| 67 | + FileWriter fileWriter = new FileWriter(file); |
| 68 | + BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); |
| 69 | + for (String line : resultList) { |
| 70 | + bufferedWriter.write(line); |
| 71 | + bufferedWriter.newLine(); |
| 72 | + } |
| 73 | + bufferedWriter.close(); |
| 74 | + } |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments