1
\$\begingroup\$

I have this Java code which I want to use to monitor file changes into directory:

import com.validation.database.entity.EntityImportRequestsTable;
import com.validation.database.service.EntityImportRequestsService;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

private static String folderPath = "D:\\Import";

public static void main(final String[] args) throws IOException, InterruptedException {

        System.out.println("Running file verifier");
        System.out.println("monitoring folder " + folderPath);
        EntityImportRequestsJob sql = new EntityImportRequestsJob();

        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path path = Paths.get(folderPath);
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        WatchKey key;
        while ((key = watchService.take()) != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
                if(event.kind().equals(StandardWatchEventKinds.ENTRY_DELETE)){
                    Instant start = Instant.now();

                    boolean flag = true;

                    while(flag) {
                        while ((key = watchService.take()) != null) {
                            HashMap<String, List> map = sql.checkFileImport();

                            List values = map.get(event.context()); // get values by file name
                            if(values.contains("Completed")){
                                // exit the monitoring while loop
                                flag = false;
                            }
                        }
                        Thread.sleep(1000);
                    }

                    Instant end = Instant.now();
                    System.out.println(Duration.between(start,end));

                    long seconds = TimeUnit.MILLISECONDS.toSeconds(Duration.between(start,end).getSeconds());
                    long minutes = TimeUnit.MILLISECONDS.toMinutes(Duration.between(start,end).getSeconds());

                    System.out.format("Execution time %d minutes %d seconds", minutes, seconds);


                }

            }
            key.reset();
        }

        watchService.close();
    }

How I can improve this code in order properly to track file import time?

\$\endgroup\$
4
  • \$\begingroup\$ Can you include your imports? \$\endgroup\$ Commented Jan 22, 2023 at 21:47
  • \$\begingroup\$ sure, post updated. \$\endgroup\$ Commented Jan 22, 2023 at 21:49
  • 2
    \$\begingroup\$ I improved this one by using Spring Boot here stackoverflow.com/a/75204176/10426557 @PeterPenzov \$\endgroup\$ Commented Jan 22, 2023 at 21:52
  • \$\begingroup\$ Do not get into a habit of comparing constants and enums with equals. Equals method removes compile time type checking as it accepts any Object as parameter. I have had the privilege of fixing a production bug where a parameter type was changed from enum to a data object, but the programmer missed an equals method so it always returned false due to type mismatch. Would have been avoided if == was used in the first place. \$\endgroup\$ Commented Jan 23, 2023 at 5:37

1 Answer 1

2
\$\begingroup\$

Generally not a good idea to hard-code a path. That should go in a config file or program arguments.

Replace println and string concatenation with printf, as in

System.out.printf("monitoring folder %s%n", folderPath);

or format(), which does the same thing and you're already using elsewhere.

If you only care about ENTRY_DELETE, then why do you register other events? Just register ENTRY_DELETE only; then you don't need to if (event.kind().equals.

Why do you sleep(1000)? Probably shouldn't.

WatchService should go in a try-with-resources.

\$\endgroup\$
2
  • \$\begingroup\$ Can you paste the complete code please? \$\endgroup\$ Commented Jan 23, 2023 at 1:50
  • 1
    \$\begingroup\$ I didn't write complete code, and I don't have your Spring stuff so I wouldn't be able to \$\endgroup\$ Commented Jan 23, 2023 at 1:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.