`
sillycat
  • 浏览: 2539142 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Monitor Directories and File(II)Timer and commons-vfs

阅读更多
Monitor Directories and File(II)Timer and commons-vfs

1. Timer and TimerTask
The Interface FileChangeListener.java:
package com.xxxx.importdata.filemonitor.timer;
public interface FileChangeListener
{
public void fileChanged(String filename);
}
The ClassFileChangeListener.java:
package com.xxxxx.importdata.filemonitor.timer;
public class ClassFileChangeListener implements FileChangeListener {
public void fileChanged(String filename) {
System.out
.println("File " + filename + " modified ,it must  reload  !");
}
}
The most import class FileMonitor.java:
package com.xxxxx.importdata.filemonitor.timer;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class FileMonitor
{
    private static final FileMonitor     instance = new FileMonitor();
    private Timer                        timer;
    private Map<String, FileMonitorTask> timerEntries;
    private FileMonitor()
    {
        this.timerEntries = new HashMap<String, FileMonitorTask>();
        this.timer = new Timer();
    }
    public static FileMonitor getInstance()
    {
        return instance;
    }
    public void addFileChangeListener(FileChangeListener listener, String filename, long period)
    {
        this.removeFileChangeListener(filename);
        FileMonitorTask task = new FileMonitorTask(listener, filename);
        this.timerEntries.put(filename, task);
        // schedule(TimerTask task,long delay,long period)
        // schedule(TimerTask task,long delay)
        // schedule(TimerTask task,Date time)
        // schedule(TimerTask task,Date firstTime,long period)
        this.timer.scheduleAtFixedRate(task, period, period);
    }
    public void removeFileChangeListener(String filename)
    {
        FileMonitorTask task = (FileMonitorTask) this.timerEntries.remove(filename);
        if (task != null)
        {
            task.cancel();
        }
    }
    private static class FileMonitorTask extends TimerTask
    {
        private FileChangeListener listener;
        private String             filename;
        private File               monitoredFile;
        private long               lastModified;
        public FileMonitorTask(FileChangeListener listener, String filename)
        {
            this.listener = listener;
            this.filename = filename;
            this.monitoredFile = new File(filename);
            if (!this.monitoredFile.exists())
            {
                return;
            }
            this.lastModified = this.monitoredFile.lastModified();
        }
        public void run()
        {
            long latestChange = this.monitoredFile.lastModified();
            if (this.lastModified != latestChange)
            {
                this.lastModified = latestChange;
                this.listener.fileChanged(this.filename);
            }
        }
    }
    public static void main(String[] args)
    {
        String path = "/home/luohua/tmp/t1.txt";
        //String path = "/home/luohua/life/work/xxxxx/xxxx-gen/records/";
        FileMonitor.getInstance().addFileChangeListener(new ClassFileChangeListener(), path, 2000);
    }
}

I am using Linux system, I notice that this lastModified can only detect the file changes. But if there are some changes in the
sub directory. It can not detect that.

And one more thing, it is said that the Timer will cost a lot. I will check if there is another better way.

2. commons-vfs
ivy.xml:
<dependency org="commons-vfs" name="commons-vfs" rev="1.0" />

the test java class is VFSMonitor.java:
package com.xxxxx.importdata.filemonitor.vfs;
import org.apache.commons.vfs.FileChangeEvent;
import org.apache.commons.vfs.FileListener;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.impl.DefaultFileMonitor;
public class VFSMonitor
{
    private static final String PATH = "/home/luohua/life/work/xxxxx/xxxx-gen/records/";
    public static void main(String[] args)
    {
        FileSystemManager fsManager = null;
        FileObject listendir = null;
        try
        {
            fsManager = VFS.getManager();
            listendir = fsManager.resolveFile(PATH);
        }
        catch (FileSystemException e)
        {
            e.printStackTrace();
        }
        DefaultFileMonitor fm = new DefaultFileMonitor(new FileListener() {
            public void fileCreated(FileChangeEvent event) throws Exception
            {
                monitor(event);
            }
            public void fileDeleted(FileChangeEvent event) throws Exception
            {
                monitor(event);
            }
            public void fileChanged(FileChangeEvent event) throws Exception
            {
                monitor(event);
            }
            private void monitor(FileChangeEvent event)
            {
                FileObject fileObject = event.getFile();
                FileName fileName = fileObject.getName();
                System.out.println(fileName + " has changed.");
            }
        });
        fm.setRecursive(true);
        fm.addFile(listendir);
        fm.start();
        try
        {
            Thread.sleep(1000000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        fm.stop();
    }
}

references:
http://www.iteye.com/topic/1096698
http://www.blogjava.net/quaff/archive/2006/03/02/33229.html
分享到:
评论

相关推荐

    FTPCLIENT_commons-net-1.4.1_jakarta-oro-2.0.8

    在IT领域,尤其是在Java编程中,FTP(File Transfer Protocol)客户端是用于与远程服务器进行文件传输的重要工具。本文将深入探讨使用Java实现FTP客户端时,如何利用`commons-net-1.4.1.jar`和`jakarta-oro-2.0.8....

    Apache Commons Compress ( commons-compress-1.15-bin.zip)

    Files.createDirectories(outputFile.getParentFile().toPath()); Files.copy(zis, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } zis.close(); ``` 除了ZIP、GZIP和7z,Apache Commons ...

    commons-net-3.3

    4. **目录管理**:`FTPClient.changeWorkingDirectory()`可切换当前工作目录,`FTPClient.listDirectories()`和`FTPClient.listFiles()`分别用于获取目录列表和文件列表。 5. **日志输出**:Apache Commons Net支持...

    java连接apache的FTP包commons-net-1.4.1.jar,jakarta-oro-2.0.8.jar

    3. **目录操作**:你可以使用`changeWorkingDirectory()`方法切换当前工作目录,`listDirectories()`和`listFiles()`方法获取目录和文件信息。 4. **设置传输模式**:`FTPClient`支持主动模式和被动模式,可以通过`...

    android实现ftp上传、下载文件,支持文件夹哦

    在Android平台上,FTP(File Transfer Protocol)是一种常用的技术,用于在服务器和客户端之间传输文件。本文将详细讲解如何在Android应用中实现FTP的文件上传和下载功能,同时支持对文件夹的操作。 首先,我们需要...

    windows版wget命令

    Logging and input file: -o, --output-file=FILE log messages to FILE. -a, --append-output=FILE append messages to FILE. -d, --debug print debug output. -q, --quiet quiet (no output). -v, --...

    wget-1.11.4-1

    Logging and input file: -o, --output-file=FILE log messages to FILE. -a, --append-output=FILE append messages to FILE. -d, --debug print lots of debugging information. -q, --quiet quiet (no output...

    windows版curl

    Logging and input file: -o, --output-file=FILE log messages to FILE. -a, --append-output=FILE append messages to FILE. -d, --debug print debug output. -q, --quiet quiet (no output). -v, --...

    dos操作系统源代码

    To build the operating system, a batch file (BUILD.BAT) is included to make life easier. This file is in the dos-c directory of the distribution. In addition, there is a corresponding batch file ...

    ls命令替代品exa.zip

    -oneline: display one entry per line-a, --all: show dot files-b, --binary: use binary (power of two) file sizes-B, --bytes: list file sizes in bytes, without prefixes-d, --list-dirs: list directories ...

    squashfs1.3r3.tar.gz

    will also append directories and files to pre-existing squashfs filesystems, see the following 'appending to squashfs filesystems' subsection. SYNTAX:mksquashfs source1 source2 ... dest [options] [-e...

    gun tar for windows

    and FILE may be a file or a device. *This* `tar' defaults to `-f- -b20'. Report bugs to &lt;tar-bugs@gnu.org&gt;. --------------------------------- @echo off copy temp"*20090424*.dat tar"bin"tar -cvf ftp...

    Reading and sorting directories with C on Linux and Unix

    Directories - Reading and sorting directories. readdir.c - Reading a directory (readdir). dirsortsize.c - Sort a directory by file size (scandir). dirsortalpha.c - Sort a directory alphabetically ...

    解决JDK1.6下的Base64报错问题

    3. 如果使用IntelliJ IDEA,File -&gt; Project Structure -&gt; Modules -&gt; Dependencies -&gt; '+' -&gt; JARs or directories,选择jar包。 4. 最后,确保在代码中正确引用jar包中的Base64类,即可解决报错问题。 通过以上...

    ftplib-4.0

    These routines allow programs access to the data streams connected to remote files and directories. FtpAccess() - Open a remote file or directory FtpRead() - Read from remote file or directory Ftp...

    Ubuntu Pocket Guide and Reference: A concise companion for day-to-day Ubuntu use

    - **File System Navigation**: The book explores the Ubuntu file system, explaining its structure and how to navigate through directories and files efficiently. - **File Manager Overview**: A thorough ...

    Wiley.Publishing.Fedora.Linux.Toolbox.1000+.Commands.for.Fedora.CentOS.and.Red.Hat.Power.Users.and.Red.Hat.Power.Users.2008.pdf

    - **File Operations**: Creating, moving, copying, and deleting files and directories using commands like `cp`, `mv`, `rm`, and `mkdir`. - **File Permissions**: Understanding and modifying file ...

    cli-essentials-bash-files-and-directories-sgharms-test-webdev-fund

    在Bash中浏览文件和目录学习目标用ls shell中的目录文件使用mv移动或重命名文件和目录使用cp复制文件touch创建空文件用mkdir新建目录用rm删除文件介绍在上一课中,我们学习了如何“导航”文件系统的目录结构。...

    squashfs2.2-r2.tar.gz

    SQUASHFS 2.2 - A squashed read-only filesystem for Linux ...exlude files/directories from the specified exclude file, one file/directory per line. If an exclude file/directory is absolute (i.e. prefixed...

    estableRuntimeException cannot be resolved 解决

    2. **IntelliJ IDEA**:类似地,选择 File -&gt; Project Structure -&gt; Modules -&gt; Dependencies -&gt; '+' -&gt; JARs or directories 添加JAR文件。 3. **Maven/Gradle**:在pom.xml(Maven)或build.gradle(Gradle)中...

Global site tag (gtag.js) - Google Analytics