5

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?

java_dev
  • 323
  • 6
  • 17
  • 1
    I've got around this by listening to file modifications too and when I don't get any for a set time interval, I declare the file fully written. It isn't perfect, but it sort of works. (By the way, you can check directly against the event kind enum, you don't need to convert it to a string.) – biziclop Jul 31 '18 at 10:28
  • Yeah there were couple of ENTRY_MODIFY after ENTRY_CREATE and I thought of using it like you did, but time interval again dragged be back, will try more on this – java_dev Jul 31 '18 at 10:43
  • 2
    please also keep in mind that it's worth checking for OVERFLOW events – diginoise Jul 31 '18 at 11:07

0 Answers0