I have a directory where a Filewatcher waits for new files.
As soon as a csv file is printed, the watcher grabs it and business logic happens.
It appears that the FileWatcher grabs the file to early when java is still writing to the file. Therefore I get an error because the FileWatcher thinks the file is incomplete.
I would like to save the data to a .tmp file and then rename the file with java WITHOUT the necessity of moving it since moving often requires copying the file.
Is there a way of doing this?
>Solution :
Files.move(from, to, StandardCopyOptions.ATOMIC_MOVE).
More generally, Files.move does what it says: It moves. However, it might implement this as ‘copy it, then delete the from‘. It tries not to.
With the ATOMIC_MOVE flag enabled, and the job can’t be done without copy-then-delete, then you simply get an exception.
So, this doesn’t so much change anything, it merely assuages your unfounded fear: If the thing you fear happens (it won’t, unless you’re doing something silly, like creating it on one file system and then ‘moving’ it to a location on another system, which, of course, cannot be done without copy-then-delete mechanics, for obvious reasons) – then you will get an exception.