What is the easiest way to track changes to a folder in Java?

I have a set of source folders. I use the Java class to create a distribution file from these folders. I would like to write another small class in Java that runs every half second, checks to see if any of the files in the folders have changed, and if so, run the building class.

So, how can I easily detect that the folder has been changed?

+5
source share
7 answers

I think you will need to check the modification time of the directory and subdirectory (for adding / deleting files) and the time the file was modified (for changes in each file).

, , . . , .

. File.lastModified()

EDIT: , Java 7 .

+4

/.

+3

Java 7, / .

JNA - . , .

+2

, , .

, .NET : FileSystemWatcher

UPDATE: kd304, , Java 7 . , .

+1

File.lastModified File.exists .

+1

NIO2 (Java7) . Java6 list() ? ( )

0

, , .

, ( -) . , , - , . . , , , , , a .

(, Apache IO FileUtils.listFiles()), . - , , .

50K 750 Linux 3Ghz. . (DJB), , . , , . - , . .

/**
 *  Provided a directory and a file extension, returns
 *  a hash using the Adler hash algorithm.
 *   
 * @param files  the Collection of Files to hash.
 * @return       a hash of the Collection.
 */
public static long getHash( Collection<File> files )
{
    Adler32 adler = new Adler32();
    StringBuilder sb = new StringBuilder();
    for ( File f : files ) {
        String s = f.getParent()+'/'+f.getName()+':'+String.valueOf(f.lastModified());
        adler.reset();
        adler.update(s.getBytes());
        sb.append(adler.getValue()+' ');
    }
    adler.reset();
    adler.update(sb.toString().getBytes());
    return adler.getValue();
}

, (, -, ). , , .

0

All Articles