How to monitor a file?

I want my program to monitor a file or directory. whenever the file or the directory is modificated, it will send an event to my program.I use a thread to check the last modification time ever 5 seconds, but i don't think this is a good design.
[259 byte] By [youhaodiyia] at [2007-11-27 6:41:36]
# 1
Have a look here: http://forum.java.sun.com/thread.jspa?threadID=5181021
Dalzhima at 2007-7-12 18:11:14 > top of Java-index,Core,Core APIs...
# 2
If i use a thread to monitor a file, when the file is changed an event will be sent. But I don't know how to implement a EventListener. How can i send a event to my program?
youhaodiyia at 2007-7-12 18:11:14 > top of Java-index,Core,Core APIs...
# 3

This should help ....

class FileChangeEventManager extends Thread

{

List<FileChangeEventListener> lst = new ArrayList<FileChangeEventListener>();

List<String> lstFiles = new ArrayList<String>();

public void fileToMonitor(String file)

{

lstFiles.add(file);

}

public void addListener()

{

// add to list

}

public void removeListener()

{

// add to list

}

public void run()

{

while(true)

{

try

{

Thread.sleep(2000);

}

catch(InterruptedException e)

{

}

// if filechanged

{

/*

* 1. create file change event object

* 2. set filename

* 3. loop through all the listener

* 4. inovke filechanged(filechangeevent obj) on all listeners

*/

}

}

}

}

class FileChangeEvent

{

String fileName;

public FileChangeEvent()

{

}

public String getFileName() {

return fileName;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

}

class FileChangeEventListener

{

public void fileChanged(FileChangeEvent e)

{

}

}

you event listeners should extends FileChangeEventListener to handle events..

enjoy !

chaos_begins_herea at 2007-7-12 18:11:14 > top of Java-index,Core,Core APIs...
# 4

How can i write a interface instead of a class to handle the event listener?

The interface looks like:

public interface FileChangeEventListener{

public void fileChanged(FileChangeEvent e);

}

In my class:

public class MyClass implements FileChangeEventListener{

public void fileChanged(FileChangeEvent e);

}

youhaodiyia at 2007-7-12 18:11:14 > top of Java-index,Core,Core APIs...
# 5
Check the following HowTo. It's an abstract class, all you need is to implement a method. You have an example for a single file or a directory. http://www.rgagnon.com/javadetails/java-0490.htmlBye.
RealHowToa at 2007-7-12 18:11:14 > top of Java-index,Core,Core APIs...