JPoller is a general-purpose Java component to poll directories and asynchronously notify the client code of incoming files. We can download it from here. This post is about using JPoller using simple codes.
The main class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package com.karlsangabriel.jpoller; import java.io.File; import org.sadun.util.polling.DirectoryPoller; public class JPollerTest { public static void main(String[] args) { File directory = new File( "C:\\Users\\ksangabr\\Desktop\\karl\\__test\\pol1"); DirectoryPoller poller = new DirectoryPoller(directory); poller.setPollInterval(1000L); poller.setBypassLockedFiles(true); try { /* poller.setFilesSortComparator( new DirectoryPoller.ModificationTimeComparator(true)); */ poller.setFilesSortComparator( new DirectoryPoller.FileSizeComparator(true)); poller.setAutoMove(false); } catch (Exception exception) { exception.printStackTrace(); } FPM pollManager = new FPM(); poller.addPollManager(pollManager); poller.setSendSingleFileEvent(true); try { poller.start(); } catch (Exception exception) { exception.printStackTrace(); } } } |
Supporting Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.karlsangabriel.jpoller; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.sadun.util.polling.BasePollManager; import org.sadun.util.polling.FileFoundEvent; public class FPM extends BasePollManager { private static File directory = new File( "C:\\Users\\ksangabr\\Desktop\\karl\\__test\\pol2"); public synchronized void fileFound(FileFoundEvent fileEvent) { File foundFile = fileEvent.getFile(); try { System.out.println( "moving - " + foundFile.getAbsolutePath()); FileUtils.moveFileToDirectory(foundFile, directory, false); Thread.sleep(1); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } |