Java如何检测文件更改 [英] Java how to detect file changes

查看:113
本文介绍了Java如何检测文件更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以触发每次文件更改都会执行某些操作的事件?
我的意思是这样(用伪代码)

Is there a way to somehow trigger an event that will do something every time a file change? I mean something like that (in pseudo code)

if(DetectedFileModified(pathToFile)){ do stuff }

我知道我可以定期执行此操作,但是我可以不用计时器吗?
我希望能够在用户更新txt文件时执行一些操作(不是通过代码,而是通过打开文件并在其中写入内容),而我不知道他什么时候会做。 / p>

I know I can do it periodically but can I somehow do it without a timer? I want to be able to make some actions when a user is updating a txt file (not via code, but just by opening the file and writing inside) and I don't know when he'll do it.

推荐答案

您需要 WatchService


WatchService API的级别很低,允许您对其进行自定义。您可以按原样使用它,也可以选择在此机制之上创建一个高级API,使其适合您的特定需求。

The WatchService API is fairly low level, allowing you to customize it. You can use it as is, or you can choose to create a high-level API on top of this mechanism so that it is suited to your particular needs.

同一位置上的Oracle博客

这篇关于Java如何检测文件更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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