处理目录中传入的文件

发布于 2024-09-07 16:01:40 字数 85 浏览 0 评论 0原文

我想制作一个Java程序,连续监视目录中是否有新文件,

如果有新文件到达,则对其进行处理,然后将其删除。

最好的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌吟 2024-09-14 16:01:40

检查新文件、处理它们、冲洗并重复:

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);
}

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);
}
挖个坑埋了你 2024-09-14 16:01:40

JDK 7 包含 java.nio.file.WatchService 类,该类允许您在文件系统发生更改时收到通知,而不是持续轮询。目前它也可在 OpenJDK 中使用:

JDK 7 功能

OpenJDK WatchService 教程

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:

JDK 7 features

OpenJDK WatchService tutorial

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文