「java监听文件变化」java 文件监听

博主:adminadmin 2022-11-25 14:08:06 54

今天给各位分享java监听文件变化的知识,其中也会对java 文件监听进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

如何用java监听数据库变化

可以使用ContentObserver对象监听,如下:

public final void registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer)

功能:为指定的Uri注册一个ContentObserver派生类实例,当给定的Uri发生改变时,回调该实例对象去处理。

参数:uri 需要观察的Uri(需要在UriMatcher里注册,否则该Uri也没有意义了)

notifyForDescendents 为false 表示精确匹配,即只匹配该Uri

为true 表示可以同时匹配其派生的Uri,举例如下:

假设UriMatcher 里注册的Uri共有一下类型:

1 、content://com.qin.cb/student (学生)

2 、content://com.qin.cb/student/#

3、 content://com.qin.cb/student/schoolchild(小学生,派生的Uri)

假设我们当前需要观察的Uri为content://com.qin.cb/student,如果发生数据变化的 Uri 为

content://com.qin.cb/student/schoolchild ,当notifyForDescendents为 false,那么该ContentObserver会监听不到,

但是当notifyForDescendents 为ture,能捕捉该Uri的数据库变化。

java如何实现linux下实时监控文件是否有变化

java 的WatchService 类提供了一种方式可以检查

try

{

WatchService watchService = FileSystems.getDefault()

.newWatchService();

Path path = Paths.get(pathName);

// 注册监听器

path.register(watchService,

StandardWatchEventKinds.ENTRY_CREATE,

StandardWatchEventKinds.ENTRY_DELETE);

while (true)

{

// 阻塞方式,消费文件更改事件

ListWatchEvent? watchEvents = watchService.take()

.pollEvents();

for (WatchEvent? watchEvent : watchEvents)

{

System.out.printf("[%s]文件发生了[%s]事件。%n", watchEvent

.context(), watchEvent.kind());

}

}

}

catch (Exception e)

{

}

Java 如何监控文件目录的变化

JavaSE 1.7提供了相关的API,去监视文件或者文件夹的变动,主要的API都在java.nio.file下面,其大概流程如下:

package org.xdemo.superutil.j2se.filewatch;

 

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;

 

import java.io.File;

import java.io.IOException;

import java.nio.file.FileSystems;

import java.nio.file.FileVisitResult;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.SimpleFileVisitor;

import java.nio.file.StandardWatchEventKinds;

import java.nio.file.WatchEvent;

import java.nio.file.WatchEvent.Kind;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.HashMap;

import java.util.Map;

 

/**

 * 文件夹监控

 * 

 * @author Goofy a href="";/a

 * @Date 2015年7月3日 上午9:21:33

 */

public class WatchDir {

 

    private final WatchService watcher;

    private final MapWatchKey, Path keys;

    private final boolean subDir;

 

    /**

     * 构造方法

     * 

     * @param file

     *            文件目录,不可以是文件

     * @param subDir

     * @throws Exception

     */

    public WatchDir(File file, boolean subDir, FileActionCallback callback) throws Exception {

        if (!file.isDirectory())

            throw new Exception(file.getAbsolutePath() + "is not a directory!");

 

        this.watcher = FileSystems.getDefault().newWatchService();

        this.keys = new HashMapWatchKey, Path();

        this.subDir = subDir;

 

        Path dir = Paths.get(file.getAbsolutePath());

 

        if (subDir) {

            registerAll(dir);

        } else {

            register(dir);

        }

        processEvents(callback);

    }

 

    @SuppressWarnings("unchecked")

    static T WatchEventT cast(WatchEvent? event) {

        return (WatchEventT) event;

    }

 

    /**

     * 观察指定的目录

     * 

     * @param dir

     * @throws IOException

     */

    private void register(Path dir) throws IOException {

        WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

        keys.put(key, dir);

    }

 

    /**

     * 观察指定的目录,并且包括子目录

     */

    private void registerAll(final Path start) throws IOException {

        Files.walkFileTree(start, new SimpleFileVisitorPath() {

            @Override

            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                register(dir);

                return FileVisitResult.CONTINUE;

            }

        });

    }

 

    /**

     * 发生文件变化的回调函数

     */

    @SuppressWarnings("rawtypes")

    void processEvents(FileActionCallback callback) {

        for (;;) {

            WatchKey key;

            try {

                key = watcher.take();

            } catch (InterruptedException x) {

                return;

            }

            Path dir = keys.get(key);

            if (dir == null) {

                System.err.println("操作未识别");

                continue;

            }

 

            for (WatchEvent? event : key.pollEvents()) {

                Kind kind = event.kind();

 

                // 事件可能丢失或遗弃

                if (kind == StandardWatchEventKinds.OVERFLOW) {

                    continue;

                }

 

                // 目录内的变化可能是文件或者目录

                WatchEventPath ev = cast(event);

                Path name = ev.context();

                Path child = dir.resolve(name);

                File file = child.toFile();

                if (kind.name().equals(FileAction.DELETE.getValue())) {

                    callback.delete(file);

                } else if (kind.name().equals(FileAction.CREATE.getValue())) {

                    callback.create(file);

                } else if (kind.name().equals(FileAction.MODIFY.getValue())) {

                    callback.modify(file);

                } else {

                    continue;

                }

 

                // if directory is created, and watching recursively, then

                // register it and its sub-directories

                if (subDir  (kind == StandardWatchEventKinds.ENTRY_CREATE)) {

                    try {

                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {

                            registerAll(child);

                        }

                    } catch (IOException x) {

                        // ignore to keep sample readbale

                    }

                }

            }

 

            boolean valid = key.reset();

            if (!valid) {

                // 移除不可访问的目录

                // 因为有可能目录被移除,就会无法访问

                keys.remove(key);

                // 如果待监控的目录都不存在了,就中断执行

                if (keys.isEmpty()) {

                    break;

                }

            }

        }

    }

 

}

关于java监听文件变化和java 文件监听的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-25,除非注明,否则均为首码项目网原创文章,转载请注明出处。