2013-03-20 81 views
6

我遵循Watching a Directory更改Java7 nio2教程,使用代碼示例WatchDir.java遞歸監視目錄的全部內容。Java 7 WatchService - 進程無法訪問該文件,因爲它正在被另一個進程使用

的代碼看起來是這樣的:

// Get list of events for the watch key. 
for (WatchEvent<?> event : key.pollEvents()) { 
// This key is registered only for ENTRY_CREATE events, but an OVERFLOW event 
// can occur regardless if events are lost or discarded. 
if (event.kind() == OVERFLOW) { 
    continue; 
} 

// Context for directory entry event is the file name of entry. 
@SuppressWarnings("unchecked") 
WatchEvent<Path> ev = (WatchEvent<Path>)event; 
Path fileName = ev.context(); 
Path fullPath = dir.resolve(fileName); 

try { 
    // Print out event. 
    System.out.print("Processing file: " + fileName); 

    processed = fileProcessor.processFile(fullPath); 

    System.out.println("Processed = " + processed); 

    if (processed) { 
     // Print out event. 
     System.out.println(" - Done!"); 
    } 
} 
catch (FileNotFoundException e) { 
    System.err.println("Error message: " + e.getMessage()); 
} 
catch (IOException e) { 
    System.err.println("Error processing file: " + fileName.toString()); 
    System.err.println("Error message: " + e.getMessage()); 
} 

好了,所以這個問題(其中我肯定做一些愚蠢的事)就在這裏:

processed = fileProcessor.processFile(fullPath); 

而且它的作用是這樣的:

public synchronized boolean processFile(Path fullPath) throws IOException { 
String line; 
String[] tokens; 
String fileName = fullPath.getFileName().toString(); 
String fullPathFileName = fullPath.toString(); 

// Create the file. 
File sourceFile = new File(fullPath.toString()); 

// If the file does not exist, print out an error message and return. 
if (sourceFile.exists() == false) { 
    System.err.println("ERROR: " + fullPathFileName + ": No such file"); 
    return false; 
} 

// Check file extension. 
if (!getFileExtension(fullPathFileName).equalsIgnoreCase("dat")) { 
    System.out.println(" - Ignored."); 
    return false; 
} 

// Process source file. 
try (BufferedReader bReader = new BufferedReader(new FileReader(sourceFile))) { 
    int type; 

    // Process each line of the file. 
    while (bReader.ready()) { 

     // Get a single line. 
     line = bReader.readLine(); 

     // Get line tokens. 
     tokens = line.split(delimiter); 

     // Get type. 
     type = Integer.parseInt(tokens[0]); 

     switch (type) { 
     // Type 1 = Salesman. 
     case 1: 
      -> Call static method to process tokes. 
      break; 
     // Type 2 = Customer. 
     case 2: 
      -> Call static method to process tokes. 
      break; 
     // Type 3 = Sales. 
     case 3: 
      -> Call static method to process tokes. 
      break; 
     // Other types are unknown! 
     default: 
      System.err.println("Unknown type: " + type); 
      break; 
     } 
    } 

    PrintStream ps = null; 
    try { 

     // Write output file. 
     // Doesn't matter. 

    } 
    finally {    
     if (ps != null) { 
      ps.close(); 
     } 
    } 
    return true; 
} 
} 

我第一次處理一個事件,它一切正常!即使有超過1個文件需要處理。但在連續的時間,我得到這個錯誤信息:

,因爲它正由另一個進程使用該進程無法訪問該文件

我在做什麼錯在這裏?我能做些什麼來處理成功的連續文件?我忘了提

兩個重要注意事項:

  1. 我使用Windows 7
  2. 當我運行在調試模式下的應用程序,它的工作原理。

編輯:如果我添加一個睡覺前我嘗試使用的文件,它的工作原理:

Thread.sleep(500); 

// Process source file. 
try (BufferedReader bReader = new BufferedReader(new FileReader(sourceFile))) { 

那麼,有沒有可能是窗口未解鎖的時間中的文件?我如何解決這個問題(以正確的方式)?

回答

14

好的,我找到了一個解決方案。我不知道這是否是這樣做的最好方法,但它是有效的。 不幸的是,即使文件仍然被Windows鎖定,file.canRead()和file.canWrite()都返回true。所以我發現,如果我嘗試用相同的名稱「重命名」它,我知道Windows是否在使用它。所以這是我做的:

while(!sourceFile.renameTo(sourceFile)) { 
     // Cannot read from file, windows still working on it. 
     Thread.sleep(10); 
    } 
+0

它的工作:) – 2016-04-06 14:11:53

+1

好戲!它幫助我了! – 2017-03-02 21:27:46

1

我有類似的問題。但是我的文件在被複制時沒有被鎖定。如果我在創建活動後立即嘗試閱讀它,那是空的。

我認爲你的情況沒有必要的技巧,你可以簡單地處理錯誤,如果你得到的錯誤比你可以執行睡眠,然後再試一次。但對我來說這不適合我。我沒有得到錯誤。所以我嘗試了你的解答,並且我明白這也是不能接受的,因爲除了閱讀,我沒有權利。所以我可以推薦我的'技巧'。我使用的是類java.io.RandomAccessFile中:

List<String> lines = null; 

while(true){ 
    try(RandomAccessFile raf = new RandomAccessFile(fileFullPath.toFile() , "r")){ 
     lines = Files.readAllLines(fileFullPath , Charset.forName(ENCODING)); 
     break; 
    }catch(FileNotFoundException ex){ 
     LOG.warn("File isn't yet completed: {}",ex.getMessage()); 
     LOG.info("Waiting {} for next attempt to read it" , SLEEP_INTERVAL_READING); 
     try { 
      Thread.sleep(SLEEP_INTERVAL_READING); 
     } catch (InterruptedException e) { 
      LOG.error("Waiting was interrupted",e); 
     } 
    }catch(Exception ex){ 
     LOG.error("Error in reading file ",ex); 
     clear(); 
     return false; 
    } 
} 
0

當事件類型的ENTRY_MODIFY請允許當前線程睡眠幾秒鐘。我不知道爲什麼會發生這種情況,但有一次在我的日誌中打印了多個ENTRY_MODIFY事件。取決於你的文件大小,請設置睡眠時間。

if(kind == StandardWatchEventKinds.ENTRY_MODIFY){ 
try { 
    Thread.sleep(1000); 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} 
//toDo - something 
} 
相關問題