0

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?

pikimota
  • 241
  • 1
  • 4
  • 15
  • 1
    How do you know that it fails? Do you get an exception or it goes with `else` path of `if` condition? – MirMasej Mar 08 '17 at 09:00
  • no exception, it goes on else path and log "file not renamed" – pikimota Mar 08 '17 at 09:04
  • 1
    Some time ago I saw somebody do a workaround: Check LASTMODIFIED to be more than 60 seconds ago from "NOW". Not a guarantee, but I think an easy approach to handle most problems with locked files. – Fildor Mar 08 '17 at 09:07
  • 2
    Have you tried to use `move` instead of [`renameTo`](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#renameTo-java.io.File-) ? – Fildor Mar 08 '17 at 09:09
  • 1
    According to [this answer](http://stackoverflow.com/a/5451161/2747533) `renameTo` is not reliable and it's better to use `move`. – MirMasej Mar 08 '17 at 09:10
  • @MirMasej How do read from that answer it is unreliable? Docs say it depends heavily on the underlying platform (OS/FS). [`Files.move`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#move-java.nio.file.Path-java.nio.file.Path-java.nio.file.CopyOption...-) does the operation in a platform-independent manner. So I agree that it may be the better choice. – Fildor Mar 08 '17 at 09:13
  • 1
    BTW judging by your description your code should pick the problematic file in next round (after 60 secs) and process it so unless you don't want such delay it should be fine. @Fildor - right, the question, answer to which I linked, says the `renameTo` is unreliable, not the answer. – MirMasej Mar 08 '17 at 09:16
  • @MirMasej ah, I see. Just read the answer. – Fildor Mar 08 '17 at 09:19

0 Answers0