1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class DirectoryLogger {
  5. /**
  6. * Logs directory operations with optional flags.
  7. * @param directoryPath The path to the directory to log.
  8. * @param operation The operation performed (e.g., "create", "delete", "list").
  9. * @param flag1 Optional first flag.
  10. * @param flag2 Optional second flag.
  11. * @param flag3 Optional third flag.
  12. */
  13. public static void logDirectoryOperation(String directoryPath, String operation, String flag1, String flag2, String flag3) {
  14. // Validate inputs
  15. if (directoryPath == null || directoryPath.isEmpty()) {
  16. System.err.println("Error: Directory path cannot be null or empty.");
  17. return;
  18. }
  19. if (operation == null || operation.isEmpty()) {
  20. System.err.println("Error: Operation cannot be null or empty.");
  21. return;
  22. }
  23. File directory = new File(directoryPath);
  24. // Log the operation
  25. System.out.println("Operation: " + operation + " on directory: " + directoryPath);
  26. if (flag1 != null && !flag1.isEmpty()) {
  27. System.out.println(" Flag 1: " + flag1);
  28. }
  29. if (flag2 != null && !flag2.isEmpty()) {
  30. System.out.println(" Flag 2: " + flag2);
  31. }
  32. if (flag3 != null && !flag3.isEmpty()) {
  33. System.out.println(" Flag 3: " + flag3);
  34. }
  35. // Perform the directory operation (example)
  36. try {
  37. if (operation.equalsIgnoreCase("create")) {
  38. if (!directory.exists()) {
  39. directory.mkdirs(); // Create the directory if it doesn't exist
  40. System.out.println(" Directory created successfully.");
  41. } else {
  42. System.out.println(" Directory already exists.");
  43. }
  44. } else if (operation.equalsIgnoreCase("delete")) {
  45. if (directory.delete()) {
  46. System.out.println(" Directory deleted successfully.");
  47. } else {
  48. System.err.println(" Failed to delete directory.");
  49. }
  50. } else if (operation.equalsIgnoreCase("list")) {
  51. List<String> files = new ArrayList<>();
  52. File[] filesArray = directory.listFiles();
  53. if (filesArray != null) {
  54. for (File file : filesArray) {
  55. files.add(file.getName());
  56. }
  57. }
  58. System.out.println(" Files in directory: " + files);
  59. } else {
  60. System.err.println("Error: Invalid operation specified.");
  61. }
  62. } catch (Exception e) {
  63. System.err.println("Error during directory operation: " + e.getMessage());
  64. e.printStackTrace();
  65. }
  66. }
  67. public static void main(String[] args) {
  68. // Example usage
  69. logDirectoryOperation("/path/to/my/directory", "create", "verbose", "timestamp", "user");
  70. logDirectoryOperation("/path/to/my/directory", "list", null, null, null);
  71. logDirectoryOperation("/path/to/my/directory", "delete", "force", null, null);
  72. }
  73. }

Add your comment