java未运行时java监控文件系统
我最近实现了 Java 7 的 WatchService,它运行得很好。现在我想知道是否有一种方法可以获取自上次运行程序以来发生的所有事件。例如:
- 我运行我的程序,创建一些文件,编辑一些文件,然后我得到所有相应的事件
- 我关闭我的程序
- 我创建一个名为
foo.txt
的文件 - 我启动我的程序,第一个事件我得到的是
foo.txt
的ENTRY_CREATE
我考虑保存 lastModifiedDate
并搜索比上次执行程序更新的文件和目录。还有另一种(更好的)方法可以做到这一点吗?
I recently implemented Java 7's WatchService and it works perfectly. Now I wondered if there is a way to get all the Events which occured since the last run of my program. For example:
- I run my program, create some files, edit some files and I get all the corresponding Events
- I close my program
- I create a file named
foo.txt
- I start my program, and the first event i get is an
ENTRY_CREATE
forfoo.txt
I thought about saving the lastModifiedDate
and searching for files and directorys newer than the last execution of my program. Is there another (and better) way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的程序要扫描所有文件更改(除了将文件存储在内容/源代码控制存储库中,但该存储在您的程序外部),则没有更好的方法来执行此操作。
Java 7 的 WatchService 只是比连续循环和比较文件日期/文件夹内容更高效的方式,因此您需要实现自己的逻辑来解决自己的问题。
There is no better way to do this if your program is meant to scan for all file changes (apart from storing files in a content / source control repository, but that would be external to your program).
Java 7's
WatchService
is only a more performant way than continuously looping and comparing file dates / folder contents, hence you need to implement your own logic to solve your own problem.在 Java 或任何其他编程语言中都无法做到这一点。
操作系统不会(也不能)缓冲文件系统事件,以防有人可能启动程序来处理它们。事件监视器/传递系统捕获正在侦听事件的正在运行的应用程序的事件。当没有任何东西在监听时,事件不会被捕获。
There is no way to do this in Java, or in any other programming language.
The operating system doesn't (and can't) buffer file system events on the off-chance that someone might start a program to process them. The event monitor / delivery system captures the events for a running application that is listening for them. When nothing is listening, the events are not captured.
您可以编写一个小型守护程序(Windows 上的系统服务),它连续运行并侦听文件系统更改。它可以将这些写入文件。当您的应用程序运行时,它可以只读取文件,而不是监听更改本身。当事件在运行时发生时,守护进程将继续接收它们并通过文件将它们发送到应用程序。
您需要确保文件的组织方式可以同时安全地写入和读取,并且不会无限期地增长。
You could write a small daemon (system service on Windows) which runs continuously and listens for file system changes. It could write these to a file. When your application runs, rather than listening for changes itself, it could just read the file. As events happen while it runs, the daemon will continue to receive them and send them through the file to the application.
You would need to ensure that the file was organised in such a way that it could be written to and read from safely at the same time, and that it did not grow indefinitely.