I want to monitor a directory, and when a file appears there open it, process it and then move it to another directory. The problem is how to check that the other program is done writing it. With Java 7, I can use a WatchService from FileSystem, but I can only check when the files are created. What I want is to know when all file handles are released.
My first thought was that I could obtain an exclusive lock, but it turned out that it was possible to kick out another application while it was actually updating the file.
What is the preferred way to do this in Java? Thanks!
The Watcher APIs currently allow you to see events when a file system object is created, modified or deleted in a watched directory. They don't tell you about other inotify events (on Linux). In fact, I don't think there is a way to do this in pure Java.
I was looking for a way to do this myself a few weeks ago and I came across a mail thread that suggested that you could write a custom implementation of the FileSystem api that provided a file watcher that supported other file system events. I decided not to pursue it because I had an alternative solution ... based on knowledge of how the files I am watching are being produced.
In my case, the files are produced by instruments that save image files to a shared drive. The solution is to watch the stream of "modified" events for a newly created file. When it stops and no more have been forthcoming for a couple of seconds (the "settling time"), then the file can be processed.
If this solution proves to be unreliable, the fallback is to implement the watching and initial processing (taking a snapshot of the file) in C / C++ using the inotify calls directly. This will allow me to directly observe the file close event.
The simplest way for a filebased interface is:
The sender writes the files with a changed filename (e.g. "example.xml_")
When the sender has finished writing the file, he renames it (e.g. "example.xml_" to "example.xml")
The receiver scans only for "*.xml"
Related
I'm trying to use Java WatchEvent ENTRY_MODIFY to check if a file is being access (ie: read, copied to clipboard). However from the documentation and a small test case I've made, that event isn't being fired. It's only fired when the file is changed.
Am I doing something wrong? If so, how can I monitor a file on the filesystem?
This isn't directly built into java. Your best bet is to jump into a native OS solution. This can be tedious if you want to support multiple systems though.
If you can get away with supporting windows take a look at THIS LINK . Scroll down to the bottom and look at similar apps. You would be interested in any app that contains a command line interface. What you will need to do is install one of the software and then kick off a process using Runtime.exec. You could potentially just use a direct dll, but I'm not qualified to tell you which dll will give you that information or if it even exists. It might be something you want to look into though if you do not want a 3rd party dependency.
You will read the results of the process that hooks into the windows dll's and will tell you if the file is currently open (See this link for more details). Your application will have to pull data (consistently asking the Application if the file is open). It is not ideal, but probably it is a potential solution.
Answering from your definition of file being accessed (copied and being read), however for file alteration there are several existing API available. Here is an example given to monitor file alteration.
To check file is copied to clipboard, you can use Clipboard#hasFiles() method when content of clipboard modified. If it returns true than file is copied to clipboard.
To check file is being read currently, you can check if the file is locked or not using implementation of FileLock abstract class. It has acquiredBy() method which returns the channel currently holding the lock on file.
you can try other libraries to accomplish that task, for example http://jnotify.sourceforge.net/
or http://java.dzone.com/announcements/new-java-library-monitor-file the latter specifically stands: File Access Monitoring- You will be able to receive notifications about events when access or modification date is changed.
Im reading a log file in Java on a Linux box on a continual schedule of 2 minutes looking for certain messages. I store the last offset (RandomAccessFile getFilePointer) and read from it onwards when I detect LastModified has changed; is this best practice or even right?
If you are using Java 7, then you can use WatchService to notify you when a File inside of a directory changes. This is similar to interrupts and doesn't need continuous polling. See this for more details on WatchService. Otherwise you are better off with the polling method you already do.
Try this Tailer:
http://commons.apache.org/io/apidocs/org/apache/commons/io/input/Tailer.html
This is Java implementation of "tail -f" Unix functionality.
For detecting changes on files, or changes in any content inside directory, you can watch that directory for new content, modification of existing content and deletion of any existing content inside any directory.
See post: Directory watching for changes in java
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 for foo.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?
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.
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.
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.
for a recent project I need to detect file system changes on a mapped Samba share from java on windows: Creates, updates and removes. At the moment I am using a folder poll that maintains a list of files and their modified timestamp to look for events.
But my problem is that this folder poll only peeks into the folder at certain times (every 10 seconds for example), so an updated file can be updated twice between two polls without recognizing.
Is there any way to get events from windows inside Java whenever a file event occours on that mappep Samba share?
Thanks!
Java doesn't have anything in the current IO api for dealing with file notifications from the O/S.
Java 7 will have a new IO API JSR-203 that has a watch file API that will either use native O/S notifications or polling if notifications are not supported to detect file changes.
In the meantime you could look to see if someone has implemented a library that allows you to hook into the O/S notifications via JNI. I think that IntelliJ IDEA uses a native lib for this purpose.
Looking on Sourceforge I've found jfilenotify but i've never used it.
Alternatively you could increase your sampling frequency (but this will start to hammer your filesystem) or change how your files are written out by adding a version number to the filename/folder so that you can easily tell when something has changed.
According to this forum entry TeamDev JNIWrapper is capable of doing this like I want it. I just purchased a copy. Thank you and
Greetz,
GHad
I have a button that I want to disable as long as there isn't a specific number of files in a directory.
Is there some kind of listener that notifies me at the moment a file is created or deleted in a directory?
There's no current native support in Java for file system events and monitoring. JNotify is a useful library for doing this. You should set it up to monitor the directory for modifications, and then determine yourself what's been added/removed.
Java 7 will have file system event support built into it.
One thing you might want to consider - If you're listening for creation events then you'll want to make sure that the file is completely written before you start reading it. I'm not sure what type of support Java 7 will offer for this problem.
I've implemented mechanisms like this in the past and this particular problem required special handling. If you are controlling both the file reader and writer then you can get around this with naming conventions, etc. (the writer names the file xxx.prt and renames the file when it's done being written). Since I didn't have control of the writer I had to add another polling mechanism to check the file size on an interval to make sure each new file was actually ready to be read. Not a perfect solution, but was sufficient for my case.
My two cents...