I want to make a Java program that monitors a directory continuously for a new file,
and if a new file arrives, process it and then delete it.
What is the best way to do this?
I want to make a Java program that monitors a directory continuously for a new file,
and if a new file arrives, process it and then delete it.
What is the best way to do this?
Check for new files, process them, rinse, and repeat:
while (true) {
File[] files = new File(DIRECTORY_PATH).listFiles();
for (File file : files) {
/* do something with this file */
//and delete it when finished
file.delete();
}
//Pause for a second before checking again
Thread.sleep(1000);
}
JDK 7 includes the java.nio.file.WatchService
class that allows you to be notified of filesystem changes when they happen rather than continuously poll. It is currently available in OpenJDK as well: