How to check if a file was added to a directory in java? [closed]

-2

I need a Java program, check if a text file has been added to a directory. Could someone help me?

    
asked by anonymous 23.06.2018 / 05:29

1 answer

2

You can use the WatchService class of the java.nio.file package.

  • Create the service:

    WatchService watcher = FileSystems.getDefault().newWatchService();

  • Record the path to be listened to. The record has to be done in a class that implements Watchable . You can use the Path class of java.nio.file .

  • //Diretório que será verificado se o arquivo foi criado

    Path diretorio = Paths.get("C:\stackoverflow");

    //registra o serviço criado

    diretorio.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

    In the register method you will pass which events you are interested in, for example, creating, removing, or changing. In your case you are only concerned with the creation, so only ENTRY_CREATE is being passed as parameter. The register method also returns a WatchKey representing the record.

  • It will be necessary to create an infinite loop that will capture the events of interest that occur in the directory and check if the file has the desired extension.
  • Events that occur in the directory are queued in WatchKey which in turn can be accessed by WatchService . The take method will return a WatchKey where some event of interest occurred.
  • WatchKey key = watcher.take();

  • Using the pollEvents method, you can access events that occurred in WatchKey .
  • Optional<WatchEvent<?>> watchEvent= key.pollEvents().stream().findFirst();

    In this case, since we are only listening to creation events, we do not need to check the event type. If we were listening to more than one event, we would also need to check the event type:

    Optional<WatchEvent<?>> watchEvent= key.pollEvents().stream().filter(event -> event.kind() == StandardWatchEventKinds.ENTRY_CREATE).findFirst();
    
  • The name of the file can be taken through the context method:
  • Path path = (Path) watchEvent.get().context();

  • The extension can be checked using the% class of Apache Commons-IO:
  • FilenameUtils

  • Finally, it is necessary to call the FilenameUtils.getExtension(path.toString()).equalsIgnoreCase("txt") method on reset so that new events continue to be captured. % W / w% has 3 states: ready , signaled , and invalid . WatchKey only accepts new events when it is in the ready state. The WatchKey is in the state of ready when it is created and after the WatchKey method is executed. After accepting an event it goes into the signaled state. In addition to these two states, it can go to the invalid state if the key registration is canceled by running the Watchkey method, if the directory becomes inaccessible, or if reset is closed. p>

  • In addition, you must verify that the cancel event occurred. This event can be captured even though we have not registered it. This can happen if the event is lost or dropped due to some unexpected behavior. Because of this it needs to be checked so that no error occurs in the code:

    WatchService OVERFLOW if (watchEvent.get().kind() == StandardWatchEventKinds.OVERFLOW) {

  • The final code looks like this:

    public static void main(String args[]) throws IOException, InterruptedException {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        //Diretório que será verificado se o arquivo foi criado
        Path diretorio = Paths.get("C:\stackoverflow");
        //registra o serviço criado
        diretorio.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
    
        while (true) {
            WatchKey key = watcher.take();
            Optional<WatchEvent<?>> watchEvent= key.pollEvents().stream().findFirst();
            if (watchEvent.isPresent()) {
                if  (watchEvent.get().kind() == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }
    
                Path path = (Path) watchEvent.get().context();
                //Verifica se o arquivo possui a extensão txt
                if (FilenameUtils.getExtension(path.toString()).equalsIgnoreCase("txt")) { 
                    System.out.println(path);
                }
            }
    
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    
        watcher.close();
    }
    
        
    25.06.2018 / 04:00