0

I drop an xml file in the scanFolder of a windows machine and java watches that file creation event and triggers my processFileMethod.

       if(event.kindOf("create") {  
           processFile (filePath);  // call process file from watcher service
       }

       processFile(Path filePath) {
             FileInputStream fileInputStream = null; 
             File inProcessFile = new File(filePath.toString());
             // inprocess file exists at this point

           try
           {
              fileInputStream = new FileInputStream(inProcessFile);
           } catch (Exception e)
           {
              // filenotfoundexception thrown.
           } finally {
             fileInputStream.close();
           }

          }

Problem

Something is holding onto the file (windows native ?). Applying a breakpoint gives it enough delay but without it raises an exception.

Tried - file.canRead, canWrite, canExecute, exists - all checks before the instantiation to verify.All return true.

Exception:

\java.io.FileNotFoundException: C:\scanFolder\File (4) - Copy.xml (The process cannot access the file because it is being used by another process)

Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39
  • 1
    Looks like you have some kind of race condition between creation of `FileInputStream` and something else which also uses that file. Say, if an external program creates the file in exclusive mode, your watcher catches that event and then tries to open the file, it may fail because of exclusive mode. Check is easy: add some delay (like `Thread.sleep(1000)`) before opening the file. If your problem goes away, then it's definitely a race condition and you should find who is using the file. – yeputons Feb 03 '17 at 05:07
  • Note that even if that helps, it's considered a very bad style to heal race conditions with sleeping. How do do that nicely is probably a separate question. – yeputons Feb 03 '17 at 05:13
  • It is the race condition @yeputons. Thanks for the hack friend, sleeping for like 30 ms. I will have to find whats holding it – Rk R Bairi Feb 03 '17 at 05:24

1 Answers1

2

The issue here is that while you are trying to create "fileInputStream = new FileInputStream (inProcessFile);" the 'other' process that created the the file hasn't finished yet. Addition of the break point gives enough delay for the process to complete and release the file hence no exception. Include if(inProcessFile.canRead()) before creating FileInputStream object.

  • InProcessFile.canRead() is always returning true, even before instantiation when let run without a breakpoint. Only sleeping a thread works :( – Rk R Bairi Feb 03 '17 at 14:36