I have an external program that write some file into a directory. Files are written approximatly every minute. I wrote a program that read these files, process them and after rename the file (actually I creaty a file copy in another directory in order that it will not be processed again). I search for the oldest file in directory through
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR)
my code for rename file is really simple
File fileRenamed = new File(PATH_FILES + "processed\\" + oldestFile.getName() + ".processed");
try {
if (oldestFile.renameTo(fileRenamed)) {
LOGGER.info(" file renamed");
} else {
LOGGER.info(" file NOT renamed!");
}
} catch (SecurityException sex) {
LOGGER.severe("security exception in file " + oldestFile.getName());
}
as you can see I rename the file and copy it into another directory ("processed"). Normally everything works fine but sometimes rename fails. I suppose is because external process haven't finished writing it and in the same time I try to rename it. My question is: is possibly to know why exactly rename fails and how to handle this situation? If the file is locked how can I unlock it?