How to poll directory to check whether new file is

2020-06-14 08:50发布

问题:

I want to poll a directory to check whether new file is added to the directory. If any new file is added I want to read that file.

Can anybody give me an idea how to do that?

回答1:

  • Java 7 has a file watcher API
  • JNotify will do it as well.


回答2:

If you are using Java 7, you can use the filesystem watch service (a new feature in Java 7).

See Oracle's tutorial that explains how to use it.

Otherwise (if you're using an older Java version) you can use a library such as Apache Commons IO. Look at the package org.apache.commons.io.monitor - it has classes to check for changes in files and directories.



回答3:

jNotify would be useful,

See Also

  • directory-listener-in-java


回答4:

Why not Apache Camel?

Here's what the code will look like:

from("file://pollingfolder?delete=true").to("bean:handleOrder");

That reads the files from "pollingfolder", deletes it upon read, and sends it to a bean called "handleOrder". Just in one line!

There's an easy way to configure it with Spring-boot automagically if you use Spring, but it can be used in plain Java as well.

Source: Apache Camel