I have a module which has to check particular directory for new file(Create). The file will be created by another system which I don't have control or visibility.
I used Java WatchService API and I am able to get event ENTRY_CREATE when there is a new file created. Below is the code.
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(dirLocation);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
if ("ENTRY_CREATE".equalsIgnoreCase(event.kind().name())) {
// File reading here
}
The problems is sometime when tried to read the new file, I am getting empty content without any exception. Searching Google and SO, I found that this might happen if the file writing is incomplete. To fix that I tried random access file,locks and creating FileOutputStream, but no luck, I got empty content without any exceptions. Finally I tried below and it worked. But my concern is, this has to be checked inside separate thread so that not blocking WatchService events and the number of thread can grow up with number of file, might be costlier operation too.
closed = file.renameTo(file);
Is there any other efficient way to check if file write operation is complete? Or is there any API available which can handle this?