如何监控 Java EE 应用程序中的文件更改?
是否有一种可移植的方法来监视文件以了解已部署应用程序的更改?
作为一个实际示例,假设我在 Glassfish AS 中部署了一个应用程序。然后,当应用程序运行时,我在 /META-INF 内部署一个配置文件,该文件将由应用程序中的某个线程读取。
那么,如何实施呢?如何监视文件(或目录)的更改?
Is there a portable way of monitoring a file for changes from a deployed application?
As a practical example, suppose that I have an application deployed in a Glassfish AS. Then, as the application runs, I deploy a configuration file inside /META-INF, which will be read by some Thread from my application.
So, how to implement this? How to monitor a file (or a directory, for that matter) for changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java7 有一个独立于平台的解决方案来监视文件系统中的文件:
http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html
以下是有关如何使用它的简短教程:
http://docs.oracle.com/javase/tutorial/essential/io/notification .html
但正如 jtahlborn 所说,如果容器没有分解 .war 文件,则没有什么可看的。
Java7 has a platform independent solution to monitor files in the filesystem:
http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html
Here is a short tutorial on how to use it:
http://docs.oracle.com/javase/tutorial/essential/io/notification.html
But as jtahlborn has correctly said, if the container does not explode the .war file, there is nothing to watch.
我认为不可能提供这样的机制。您假设“/META-INF”位于文件系统上,但我不认为 Java EE 应用程序需要分解到文件系统。 (是的,许多应用程序服务器出于各种充分的原因这样做,但我很确定这不是必需的)。
I think it would be impossible to provide such a mechanism. You are assuming "/META-INF" is on the file system, but i don't believe there is any requirement for a Java EE application to be exploded to the filesystem. (yes, many app servers do that for a variety of good reasons, but i'm pretty sure that is not a requirement).
类加载器会大量缓存,并且第一次读取时资源不再从底层文件系统更新。
无论如何,您都不允许在纯 Java EE 中访问和操作文件系统。原因很简单 - 如果您的线程迁移到另一个节点(对于集群服务器),您的文件将不再可用。容器必须了解这些事情,以便能够正确处理它们,而文件系统不是“这些事情”之一。
Classloaders cache heavily and a resource when first read is not updated anymore from the underlying filesystem.
Regardless, you are not allowed to access and manipulate the file system in pure Java EE. The reason is simple - if your thread is migrated to another node (for clustered serveres) your files will not be available anymore. The container must know about these things so it can handle them properly, and filesystems are not one of "these things".
请检查@jtahlborn 的答案。如果您确实有权访问文件系统,那么您有两种选择:
可移植的低效方法是定期轮询文件系统并检查更改,方法是检查修改日期或检查文件中的 CRC(速度较慢)
有效的方法是使用本机操作系统功能在文件更改时收到通知。查看 libnotify。然而,它将需要本地本机库。
Please check the answer from @jtahlborn. If you do have access to the filesystem, then you have two choices:
The portable inefficient way is to periodically poll the filesystem and check for changes, either by checking the modification date or CRCins the file (slower)
The efficient way is to use the native OS functionalities to be notified when the file changes. Check out libnotify. It's going to require local native libraries, however.