-2
I need a program in Java, check if in a directory was added some text file. Could someone help me ?
-2
I need a program in Java, check if in a directory was added some text file. Could someone help me ?
3
You can use the class WatchService
package java.nio.file
.
Create the service:
WatchService watcher = FileSystems.getDefault().newWatchService();
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.
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();
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();
context
:Path path = (Path) watchEvent.get().context();
FilenameUtils
of Apache Commons-IO:FilenameUtils.getExtension(path.toString()).equalsIgnoreCase("txt")
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.
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 java filing-cabinet directory
You are not signed in. Login or sign up in order to post.
Any file? It is yours! You need to listen to the directory or just confirm the writing of the file!
– Jefferson Quesado
Any file, could give an example of how to listen to the directory ?
– Elvis Serafim