2010-03-15 85 views
4

我想知道如何有效地实现java中的文件系统更改?假设我在文件夹中有一个文件并修改该文件。我希望尽快通过java通知有关此更改(如果可能,请不要频繁轮询)。如何检测java中的文件系统已更改

因为我认为我可以每隔几秒钟拨打java.io.file.lastModified,但我不喜欢那个解决方案的声音。

[email protected]:~/testje$ java -version 
java version "1.6.0_18" 
Java(TM) SE Runtime Environment (build 1.6.0_18-b07) 
Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode) 

回答

8

看看JNotify,它执行这种类型的监测。

对于这类工作,Java 7将拥有一些更高级的API(WatchService),这将消除对支持此功能的操作系统的轮询。

+1

IIRC,JNotify需要操作系统特定的DLL。虽然可能不如性能(是的,还不是一个真正的词),JPoller提供了一个纯粹的Java实现。 – 2010-03-15 22:39:50

+0

因此,直到使用Java7时,我总是有点破解,因为我认为Jpoller民意调查很疯狂。 JNotify不是原生的。 – Alfred 2010-03-15 23:02:32

+0

不太确定您的意思是JNotify不是原生的。它确实需要特定于操作系统的DLL /库。 – 2010-03-15 23:04:00

1

我怀疑有一个纯java的方式来做到这一点。操作系统提供API来监视文件系统的活动。您可能需要调用这些API。

+0

我没有看过它,但认为它实际上是它们在Java7中的新文件系统API中解决的一部分。在一天结束时,它当然需要文件系统或操作系统本身的支持。 – Fredrik 2010-03-15 22:36:19

1

使用JNotify,你需要做的就是在buildpath中添加jnotify.jar并且放入两个dll文件,例如jnotify.dll jnotify_64bit.dll和jdk的lib文件。一个演示程序是

package jnotify; 

import net.contentobjects.jnotify.JNotify; 
import net.contentobjects.jnotify.JNotifyListener; 

public class MyJNotify { 
    public void sample() throws Exception { 
    String path = "Any Folder location here which you want to monitor"; 
    System.out.println(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"); 
    } 
} 

class Listener implements JNotifyListener { 
    public void fileRenamed(int wd, String rootPath, String oldName, 
      String newName) { 
     print("renamed " + rootPath + " : " + oldName + " -> " + newName); 
    } 

    public void fileModified(int wd, String rootPath, String name) { 
     print("modified " + rootPath + " : " + name); 
    } 

    public void fileDeleted(int wd, String rootPath, String name) { 
     print("deleted " + rootPath + " : " + name); 
    } 

    public void fileCreated(int wd, String rootPath, String name) { 
     print("created " + rootPath + " : " + name); 
    } 

    void print(String msg) { 
     System.err.println(msg); 
    } 
} 
public static void main(String[] args) { 
    try { 
     new MyJNotify().sample(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
} 
1

有一个用于执行文件系统监视的Apache软件包:commons.io.monitor。

Documentation

An example

从我可以告诉,你仍然需要轮询尽管你有在频率控制。