Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: WatchService - small code for monitoring folders

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default WatchService - small code for monitoring folders

    I'm very new to Java. I found and example of a folder watcher service that I wanted to use for a simple app but no matter what I do I cannot get it to work. As best as I can figure out is that I'm not assigning the path variable properly.

    I'd also be very grateful if someone could explain why I have to specify the full java.nio.file.StandardWatchEventKind.ENTRY_CREATE even though I do the import at the beginning.


    import java.io.*;
    import java.io.IOException;
    import java.nio.file.FileSystem;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
    import java.nio.file.StandardWatchEventKind.*;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
     
    public class FileWatcher {
    	public static void main(String args[]) throws InterruptedException {	
     
    FileSystem fs = FileSystems.getDefault();
    WatchService watcher = null;
    try {
    	watcher = fs.newWatchService();
    } catch (IOException ex) {
    	System.err.println(ex);
    }
    Path dir = FileSystems.getDefault().getPath("H:\\Download");
    System.out.println(dir.toString());
    try {
        WatchKey key = dir.register(watcher, java.nio.file.StandardWatchEventKind.ENTRY_CREATE);
    } catch (IOException x) {
        System.err.println(x);
    }
    for (;;) {
     
        //wait for key to be signaled
        WatchKey key = watcher.take();
     
     
        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
     
            //The filename is the context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path filename = ev.context();
            System.out.println(ev.kind() + " : " + ev.context());
        }
     
        //Reset the key -- this step is critical if you want to receive
        //further watch events. If the key is no longer valid, the directory
        //is inaccessible so exit the loop.
        boolean valid = key.reset();
        System.out.println(valid);
        if (!valid) {
            break;
        }
    }
     
     
     
    }
    }


  2. #2
    Member Truffy's Avatar
    Join Date
    May 2009
    Location
    Philippines
    Posts
    93
    Thanks
    2
    Thanked 9 Times in 7 Posts

    Default Re: WatchService - small code for monitoring folders

    what error does it show?

  3. #3
    Junior Member
    Join Date
    Mar 2011
    Posts
    5
    My Mood
    Cheerful
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: WatchService - small code for monitoring folders

    Use / instead of \\

  4. #4
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: WatchService - small code for monitoring folders

    I've changed the code now to the following and all the functionality that I wanted is in there and it works. The only problem I have with it is that it simply kind of freezes after a while (maybe an hour or so). I have no idea why. There are no error messages or anything like that, it just stops monitoring the folder. The frame still remains on the screen though.

    import net.contentobjects.jnotify.JNotify;
    import net.contentobjects.jnotify.JNotifyListener;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.awt.Dimension;
    import java.awt.Toolkit;
     
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import java.util.logging.*;
    import java.awt.BorderLayout;
     
    public class FileWatcher extends JPanel {
    	// private static String line2 = "error";
    	private JFrame frame = new JFrame();
    	private JTextArea textArea = new JTextArea();
    	private JScrollPane pane = new JScrollPane(textArea);
    	private static FileWatcher watcher = new FileWatcher();
     
    	// private String path;
    	private void sample(String path) throws Exception {
    		// System.out.println(path);
    		showInfo("Monitoring: " + path);
    		int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED
    				| JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
    		boolean watchSubtree = true;
    		int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
     
    		Thread.sleep(1000000);		
     
                                    boolean res = JNotify.removeWatch(watchID);
    		if (!res) {
    			// System.out.println("Invalid");
    			showInfo("Invalid");
    		}
    	}
     
    	public void TouchFile(String fName) {
    		if ((fName.indexOf("Thumbs") == -1) && (fName.indexOf(".rar") == -1)
    				&& (fName.indexOf(".part") == -1)) {
    			String TodayDate = "";
    			String fModifyDate = "";
    			String line;
    			String line2 = "error";
    			Calendar calendar = Calendar.getInstance();
    			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    			File filename = new File(fName);
    			try {
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			TodayDate = dateFormat.format(calendar.getTime());
    			fModifyDate = dateFormat.format(filename.lastModified());
    			try {
    				Thread.currentThread().sleep(1000);
    				// showInfo(line2 + "  " + (!fModifyDate.equals(TodayDate)));
     
    				while ((line2.indexOf("error") != -1)
    						&& (!fModifyDate.equals(TodayDate))) {
    					// System.out.println(fName + " modified on: " +
    					// fModifyDate);
    					line2 = " ";
    					line = " ";
    					Process p = Runtime.getRuntime().exec(
    							"C:\\Users\\BLUE\\Documents\\MYDROP~1\\Utils\\WatchFolder\\touch.exe "
    									+ "\"" + fName + "\"");
    					// Process p = Runtime.getRuntime().exec("touch.exe " + "\""
    					// + fName + "\"");
    					BufferedReader input = new BufferedReader(
    							new InputStreamReader(p.getInputStream()));
    					while ((line = input.readLine()) != null) {
    						line2 = line2 + "\n" + line;
    					}
    					input.close();
    					// System.out.println(line2);
    					p.waitFor();
    					showInfo(line2);
    				}
    				showInfo(fName + " modified on: " + fModifyDate);
    			} catch (Exception err) {
    				err.printStackTrace();
    			}
    		}
    	}
     
    	public void showInfo(String data) {
    		watcher.textArea.append(data + "\n");
    		watcher.frame.getContentPane().validate();
    		watcher.textArea.setCaretPosition(watcher.textArea.getText().length() - 1);
    	}
     
    	class Listener implements JNotifyListener {
    		public void fileRenamed(int wd, String rootPath, String oldName,
    				String newName) {
    			// print("renamed " + rootPath + " : " + oldName + " -> " +
    			// newName);
    			showInfo("renamed " + rootPath + "\\" + oldName + " -> " + newName);
    		}
     
    		public void fileModified(int wd, String rootPath, String name) {
    			// print("modified " + rootPath + " : " + name);
    			TouchFile(rootPath + "\\" + name);
    			// showInfo("modified " + rootPath + "\\" + name);
    		}
     
    		public void fileDeleted(int wd, String rootPath, String name) {
    			// print("deleted " + rootPath + " : " + name);
    			showInfo("deleted " + rootPath + "\\" + name);
    		}
     
    		public void fileCreated(int wd, String rootPath, String name) {
    			// print("created " + rootPath + " : " + name);
    			TouchFile(rootPath + "\\" + name);
    			showInfo("created " + rootPath + "\\" + name);
    		}
     
    		void print(String msg) {
    			// System.err.println(msg);
    			showInfo(msg);
    		}
    	}
     
    	public static void main(String[] args) {
    		String path = "H:\\download";
    		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    		watcher.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		watcher.frame.setSize(500, 200);
    		watcher.frame.setVisible(true);
    		watcher.frame.getContentPane().add(watcher.pane);
    		watcher.frame.setVisible(true);
    		watcher.frame.setLocation(screenSize.width - 500,
    				screenSize.height - 250);
    		try {
    			if (args.length > 0) {
    				new FileWatcher().sample(args[0]);
    			} else {
    				new FileWatcher().sample(path);
     
    			}
     
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    Last edited by zincc; March 8th, 2011 at 02:53 AM.

  5. #5
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: WatchService - small code for monitoring folders

    I've found the following comment (for the Thread.sleep line of code) that I had deleted previously. Can someone explain to me what it means please. My application freezes regardless of this line of code but I think the key to why it does might lie here.

    // sleep a little, the application will exit if you         
    // don't (watching is asynchronous), depending on your         
    // application, this may not be required         
    Thread.sleep(1000000);
    Last edited by zincc; March 8th, 2011 at 02:49 AM.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,307
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: WatchService - small code for monitoring folders

    I've found the following comment (for the Thread.sleep line of code) that I had deleted previously. Can someone explain to me what it means please.
    See the API (Thread (Java Platform SE 6)), Threed.sleep causes the current thread to..well, sleep - stops the execution of the current thread. In this code above, for 1 million milliseconds.

Similar Threads

  1. Monitoring thread for progress bar.
    By relixus in forum Threads
    Replies: 1
    Last Post: October 4th, 2010, 12:08 AM
  2. Replies: 2
    Last Post: August 1st, 2010, 06:29 AM
  3. Small Project
    By 3XiLED in forum Paid Java Projects
    Replies: 7
    Last Post: March 1st, 2010, 07:35 AM
  4. Monitoring program
    By jassi in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 7th, 2010, 11:29 PM
  5. small problem ... I need help
    By Ashar in forum Loops & Control Statements
    Replies: 4
    Last Post: December 4th, 2009, 10:26 AM