How to check if a file has been added to a java directory?

Asked

Viewed 496 times

-2

I need a program in Java, check if in a directory was added some text file. Could someone help me ?

  • Any file? It is yours! You need to listen to the directory or just confirm the writing of the file!

  • Any file, could give an example of how to listen to the directory ?

1 answer

3


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

  1. Create the service:

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

  2. Record the path that will be heard. Registration has to be done in a class that implements Watchable. You can use the class Path 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 method register you will pass on what events you are interested in, for example, creation, removal or change. In your case you are only concerned with creating, so just the ENTRY_CREATE is being passed as parameter. The method register also returns a WatchKey representing the record held.

  1. You will need 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.
  2. Events that occur in the directory are lined up in the WatchKey which in turn can be accessed by WatchService. The method take will return a WatchKey where an event of interest has taken place.

WatchKey key = watcher.take();

  1. By the method pollEvents it is possible to access the events that occurred in the WatchKey.

Optional<WatchEvent<?>> watchEvent= key.pollEvents().stream().findFirst();

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

Optional<WatchEvent<?>> watchEvent= key.pollEvents().stream().filter(event -> event.kind() == StandardWatchEventKinds.ENTRY_CREATE).findFirst();
  1. The name the file can be picked up through the method context:

Path path = (Path) watchEvent.get().context();

  1. The extension can be checked using the class FilenameUtils of Apache Commons-IO:

FilenameUtils.getExtension(path.toString()).equalsIgnoreCase("txt")

  1. Finally, it is necessary to call the method reset in WatchKey so that new events continue to be captured. A WatchKey has 3 states: ready, signaled and invalid. To WatchKey only accepts new events when in the state of ready. To Watchkey is in the state of ready when it is created and after the execution of the method reset. After accepting an event she goes to the state of signaled. Beyond these two states she can go to the state invalid if the key record is canceled by executing the method cancel, if the directory becomes inaccessible or WatchService is closed.

  2. In addition, it is necessary to verify whether the event of OVERFLOW. This event can be captured even though we haven’t recorded it. This can happen if the event is lost or discarded due to some unexpected behavior. Because of this it needs to be checked so that no error occurs in the code:

    if (watchEvent.get().kind() == StandardWatchEventKinds.OVERFLOW) { continue; }

The final code stays that way:

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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.