I need a Java program, check if a text file has been added to a directory. Could someone help me?
I need a Java program, check if a text file has been added to a directory. Could someone help me?
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.
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();
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();
context
method: Path path = (Path) watchEvent.get().context();
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();
}