FileInputstream - FileNotFound(进程无法访问文件)。适用于断点

时间:2017-02-03 04:52:14

标签: java file filenotfoundexception fileinputstream file-watcher

我将一个xml文件放在windows机器的scanFolder中,java监视该文件创建事件并触发我的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();
           }

          }

问题

有什么东西保留在文件上(Windows native?)。应用断点会给它足够的延迟但没有它会引发异常。

尝试 - file.canRead,canWrite,canExecute,exists - 在实例化之前进行所有检查以验证。所有返回true。

例外

\ java.io.FileNotFoundException:C:\ scanFolder \ File(4) - Copy.xml(进程无法访问该文件,因为它正由另一个进程使用)

1 个答案:

答案 0 :(得分:2)

这里的问题是,当你试图创建“fileInputStream = new FileInputStream(inProcessFile);”创建该文件的“其他”进程尚未完成。添加断点为进程完成和释放文件提供了足够的延迟,因此没有例外。在创建FileInputStream对象之前包含if(inProcessFile.canRead())。