1. import java.io.*;
  2. import java.util.*;
  3. public class DuplicateRemover {
  4. public static void removeDuplicates(String inputFilePath, String outputFilePath, boolean dryRun) throws IOException {
  5. // Use a Set to store unique lines. Set automatically handles duplicates.
  6. Set<String> uniqueLines = new HashSet<>();
  7. try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
  8. BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
  9. String line;
  10. while ((line = reader.readLine()) != null) {
  11. if (uniqueLines.add(line)) { // add() returns true if element was not already present
  12. writer.write(line);
  13. writer.newLine();
  14. }
  15. }
  16. if(dryRun){
  17. System.out.println("Dry run mode is active. No changes were made.");
  18. } else {
  19. System.out.println("Duplicates removed. Output written to: " + outputFilePath);
  20. }
  21. }
  22. }
  23. public static void main(String[] args) throws IOException {
  24. if (args.length != 2) {
  25. System.out.println("Usage: java DuplicateRemover <input_file_path> <output_file_path> [dryRun (true/false)]");
  26. return;
  27. }
  28. String inputFilePath = args[0];
  29. String outputFilePath = args[1];
  30. boolean dryRun = false;
  31. if(args.length == 3){
  32. dryRun = args[2].equalsIgnoreCase("true");
  33. }
  34. try {
  35. removeDuplicates(inputFilePath, outputFilePath, dryRun);
  36. } catch (IOException e) {
  37. System.err.println("Error processing files: " + e.getMessage());
  38. e.printStackTrace();
  39. }
  40. }
  41. }

Add your comment