Я следил за 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;
}
}
В первый раз, когда я обрабатываю событие, все работает отлично! Даже если обрабатывается более одного файла. Но в раз подряд, я получаю сообщение об ошибке:
Процесс не может получить доступ к файлу, так как он используется другим процессом
Что я здесь делаю неправильно? Что я могу сделать для обработки последовательных файлов с успехом?
Два важных замечания, что я забыл упомянуть:
- Я использую Windows 7.
- При запуске приложения в режиме отладки, это работает.
EDIT: Если я добавить сон, прежде чем я пытаюсь использовать файл, он работает:
Thread.sleep(500);
// Process source file.
try (BufferedReader bReader = new BufferedReader(new FileReader(sourceFile))) {
Итак, можно ли быть для Windows, не открывая файлы во времени? Как я могу исправить это (правильно)?
это работа вокруг: –
Приятный трюк! Это помогло мне! –