我遵循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個文件需要處理。但在連續的時間,我得到這個錯誤信息:
,因爲它正由另一個進程使用該進程無法訪問該文件
我在做什麼錯在這裏?我能做些什麼來處理成功的連續文件?我忘了提
兩個重要注意事項:
- 我使用Windows 7
- 當我運行在調試模式下的應用程序,它的工作原理。
編輯:如果我添加一個睡覺前我嘗試使用的文件,它的工作原理:
Thread.sleep(500);
// Process source file.
try (BufferedReader bReader = new BufferedReader(new FileReader(sourceFile))) {
那麼,有沒有可能是窗口未解鎖的時間中的文件?我如何解決這個問題(以正確的方式)?
它的工作:) – 2016-04-06 14:11:53
好戲!它幫助我了! – 2017-03-02 21:27:46