我正在使用Watcher Service让我注意添加或删除特定目录中的文件。到目前为止,我已经将它用于添加文件和删除文件。然而,当我添加文件,删除该文件,然后再次重试添加该文件时,我看到的是堆栈跟踪(java.io.FileNotFoundException: C:\data\index.php (The process cannot access the file because it is being used by another process)
。
以下是我的getDigest方法的try
块中发生错误的相关代码:
public class WatchDir implements Runnable{
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
if(!Files.isDirectory(child, NOFOLLOW_LINKS)){
//Callable<LftFile> worker;
try {
**this.file = new LftFile(child.toFile(), kind != ENTRY_CREATE);**
if(this.file.isDeleted()){
// Update DB, set deleted flag
} else {
// Add to DB
}
} catch (Exception e1) {
logger.error("...");
}
}
...
...
}
}
// this is a method within the LftFile. It reads in the file's content
// and creates a crc on it. This is for future validation.
private static long getDigest(File f) {
long crc = -1;
try ( **InputStream in = new FileInputStream(f)** ) { // <--- ERRS HERE
CRC32 crcMaker = new CRC32();
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = in.read(buffer)) != -1) {
crcMaker.update(buffer, 0, bytesRead);
}
crc = crcMaker.getValue();
} catch (Exception e) {
e.printStackTrace();
}
return crc;
}