I have a use case as per which, my module which is running over Linux file system should be notified of any new file in remote windows share.
Is there any built in functionality for this? I have done some basic Googling and found some filewatcher (Filesystemwatcher in C#) sort of thing.
Is it useful for Java 6? How easy and efficient it will be for a FTP call where I have to download the file as and when it appears.
Thanks.
There is a file watcher as of java 7. See here for the trail on this. I am not sure if this works over remote windows shares so it might be worth experimenting a bit with it.
If you cannot use java 7 then it might be worth using the ScheduledExecutor (as of java 5) and manually check every x seconds the remote directory
Not sure if the library you suggested needs java 7 or not. It;s not too hard to write something that scans so I have written it below for you in a unit test. I have not tested it so it may have a couple of bugs in but it should be almost there. It basically scans a directory every second and then will print to sysout files that have been added or removed. It checks the directory you specify and all subdirectories.
public void test() {
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
scanDirectory(new File("."));
}}, 1, 1, TimeUnit.SECONDS);
}
private void scanDirectory(File directory) {
Set<File> before = new HashSet<File>();
Set<File> after = new HashSet<File>();
addFiles(directory, after);
for (File f :after) {
if (!before.contains(f)) {
System.out.format("new file added %s", f);
}
}
for (File f :before) {
if (!after.contains(f)) {
System.out.format("file removed %s", f);
}
}
before.clear();
before.addAll(after);
}
private void addFiles(File file, Collection<File> allFiles) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
allFiles.add(f);
addFiles(f, allFiles);
}
}
}