如何检查文件是否在Java中持续存在? [英] How to check whether files are there or not continuously in Java?

查看:173
本文介绍了如何检查文件是否在Java中持续存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算让程序继续检查目录是否存在文件。如果没有等待一段时间(比如说5分钟睡眠),然后再检查目录。程序必须保持运行并且不应该结束。

I'm planning to make a program to keep checking the directory whether files exists or not. If not then wait for some time (say 5 mins sleep) and then again checks the directory. The program must keep running and should not end.

我想过要做一个多线程程序。但不知道我能如何实现它。如果有任何其他选项可用,请让我知道。

I've thought of make a multi-thread program. But don't know how exactly I can implement it. And if any other options are available then please let me know.

推荐答案


要实现此功能,称为文件更改通知,程序必须能够检测到文件系统上的相关目录发生了什么。一种方法是轮询文件系统寻找变更,但是这种方法效率低下。它不会扩展到具有数百个打开的文件或目录来监视的应用程序。

To implement this functionality, called file change notification, a program must be able to detect what is happening to the relevant directory on the file system. One way to do so is to poll the file system looking for changes, but this approach is inefficient. It does not scale to applications that have hundreds of open files or directories to monitor.

java.nio.file包提供了一个名为Watch Service的文件更改通知API API。该API使您能够使用手表服务注册目录(或目录)。注册时,告诉服务您感兴趣的事件类型:文件创建,文件删除或文件修改。当服务检测到感兴趣的事件时,它被转发到注册的进程。注册的进程有一个线程(或一个线程池)专用于监视其注册的任何事件。当事件进入时,根据需要进行处理。

The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.

您可以通过创建手表服务和注册各种活动来实现。有关详细信息,请参见 Oracle教程文档

You can do so by creating a watch service and registering for various events. More details can be found here at Oracle tutorial doc.

SO的类似问题这里

这篇关于如何检查文件是否在Java中持续存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆