加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java程序监视目录

发布时间:2020-12-15 01:07:18 所属栏目:Java 来源:网络整理
导读:嘿家伙我想创建一个程序,24/7监视一个目录,如果一个新文件添加到它,那么如果文件大于10mb,它应该排序.我已经实现了我的目录的代码,但我不知道如何在每次添加新记录时检查目录,因为它必须以连续的方式发生. import java.io.*;import java.util.Date;public cl

嘿家伙我想创建一个程序,24/7监视一个目录,如果一个新文件添加到它,那么如果文件大于10mb,它应该排序.我已经实现了我的目录的代码,但我不知道如何在每次添加新记录时检查目录,因为它必须以连续的方式发生.

import java.io.*;
import java.util.Date;

public class FindingFiles {

    public static void main(String[] args) throws Exception {

        File dir = new File("C:UsersMayankDesktopjava princeton");// Directory that contain the files to be searched 
        File[] files= dir.listFiles();
        File des=new File("C:UsersMayankDesktopnewDir");  // new directory where files are to be moved 

        if(!des.exists())
        des.mkdir();

        for(File f : files ){
            long diff = new Date().getTime() - f.lastModified();

            if( (f.length() >= 10485760) || (diff > 10 * 24 * 60 * 60 * 1000) )
            {
                f.renameTo(new File("C:UsersmayankDesktopnewDir"+f.getName()));

            }  }  
}
}
最佳答案
手表服务应符合您的需求:https://docs.oracle.com/javase/tutorial/essential/io/notification.html

以下是实施监视服务所需的基本步骤:

>为文件系统创建WatchService“观察者”.
>对于要监视的每个目录,请将其注册到观察程序.注册目录时,您可以指定要通知的事件类型.您为每个注册的目录收到一个WatchKey实例.
>实现无限循环以等待传入事件.当事件发生时,密钥将发出信号并放入观察者的队列中.
从观察者的队列中检索密钥.您可以从密钥中获取文件名.
>检索密钥的每个待处理事件(可能有多个事件)并根据需要进行处理.
>重置密钥,然后继续等待事件.
>关闭服务:当线程退出或关闭时(通过调用其关闭的方法),监视服务退出.

作为旁注,您应该支持自Java 7以来可用的java.nio包来移动文件.

renameTo()有一些严重的限制(从Javadoc中提取):

Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another,it might not be atomic,and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.

例如,在Windows上,如果目标目录存在,renameTo()可能会失败,即使它是空的.
此外,该方法可能在失败时返回布尔值而不是异常.
通过这种方式,可能很难猜测问题的根源并在代码中处理它.

这是一个执行您的需求的简单类(它处理所有步骤,但不一定需要Watch Service关闭).

package watch;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WatchDir {

    private final WatchService watcher;
    private final Map

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读