监视目录的java程序
我想创建一个24/7监控目录的程序,如果向其中添加了新文件,那么如果文件大于10mb,它应该对其进行排序。我已经为我的目录实现了代码,但我不知道如何让它在每次添加新记录时检查目录,因为它必须以连续的方式进行监视目录的java程序,java,directory,Java,Directory,我想创建一个24/7监控目录的程序,如果向其中添加了新文件,那么如果文件大于10mb,它应该对其进行排序。我已经为我的目录实现了代码,但我不知道如何让它在每次添加新记录时检查目录,因为它必须以连续的方式进行 import java.io.*; import java.util.Date; public class FindingFiles { public static void main(String[] args) throws Exception { File
import java.io.*;
import java.util.Date;
public class FindingFiles {
public static void main(String[] args) throws Exception {
File dir = new File("C:\\Users\\Mayank\\Desktop\\java princeton");// Directory that contain the files to be searched
File[] files= dir.listFiles();
File des=new File("C:\\Users\\Mayank\\Desktop\\newDir"); // 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:\\Users\\mayank\\Desktop\\newDir\\"+f.getName()));
} }
}
}
手表服务应符合您的需要: 以下是实现watch服务所需的基本步骤:
- 为文件系统创建WatchService“watcher”。
- 对于要监视的每个目录,请向watcher注册它。注册目录时,请指定要通知的事件类型。对于您注册的每个目录,您都会收到一个WatchKey实例。
- 实现无限循环以等待传入事件。当一个事件发生时,密钥会被发送信号并放入观察者的队列中。
从观察者队列中检索密钥。您可以从密钥获取文件名。
- 检索密钥的每个挂起事件(可能有多个事件)并根据需要进行处理。
- 重置按键,然后继续等待事件。
- 关闭服务:当线程退出或关闭(通过调用其关闭方法)时,监视服务退出。
作为补充说明,您应该支持自java 7以来提供的
java.nio
包来移动文件。renameTo()
有一些严重的限制(摘自Javadoc):
此方法行为的许多方面都是固有的
平台相关:重命名操作可能无法移动
从一个文件系统到另一个文件系统,它可能不是原子的,而且
如果文件的目标抽象路径名为
已经存在。应始终检查返回值以确保
重命名操作已成功
例如,在Windows上,如果目标目录存在,renameTo()
可能会失败,即使它是空的此外,该方法在失败时可能返回布尔值,而不是异常。
这样,就很难猜测问题的根源并在代码中进行处理。
下面是一个简单的类,它执行您的需求(它处理所有步骤,但不一定需要关闭监视服务)
packagewatch;
导入静态java.nio.file.StandardWatchEventTypes.ENTRY\u创建;
导入java.io.File;
导入java.io.IOException;
导入java.nio.file.FileSystems;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.nio.file.WatchEvent;
导入java.nio.file.WatchKey;
导入java.nio.file.WatchService;
导入java.util.Date;
导入java.util.HashMap;
导入java.util.Map;
公共类WatchDir{
私人最终观察者服务观察者;
私有最终映射密钥;
专用路径targetDirPath;
专用路径;
WatchDir(文件sourceDir,文件targetDir)引发IOException{
this.watcher=FileSystems.getDefault().newWatchService();
this.keys=new HashMap();
this.sourceDirPath=path.get(sourceDir.toURI());
this.targetDirPath=path.get(targetDir.toURI());
WatchKey key=sourceDirPath.register(watcher,ENTRY\u CREATE);
keys.put(key,sourceDirPath);
}
公共静态void main(字符串[]args)引发IOException{
//包含要搜索的文件的目录
文件目录=新文件(“C:\\Users\\Mayank\\Desktop\\java princeton”);
//要移动文件的新目录
File des=新文件(“C:\\Users\\Mayank\\Desktop\\newDir”);
如果(!des.exists())
des.mkdir();
//注册目录并处理其事件
新的WatchDir(dir,des).processEvents();
}
/**
*处理排队给观察者的密钥的所有事件
*
*@抛出异常
*/
私有void processEvents()引发IOException{
对于(;;){
//等待钥匙发出信号
监视键;
试一试{
key=watcher.take();
}捕捉(中断异常x){
返回;
}
Path dir=keys.get(key);
if(dir==null){
System.err.println(“未识别WatchKey!!”;
继续;
}
for(WatchEvent事件:key.pollEvents()){
WatchEvent.Kind-Kind=event.Kind();
//目录条目事件的上下文是条目的文件名
@抑制警告(“未选中”)
WatchEvent ev=(WatchEvent)事件;
路径名=ev.context();
路径子项=目录解析(名称);
//打印输出事件
System.out.format(“%s:%s\n”,event.kind().name(),child);
//这是在文件夹中修改的文件或文件夹
File filecatch=child.toFile();
//在这里,您可以调用在上执行测试的代码
//调整文件大小,使文件移动
long diff=new Date().getTime()-filecatch.lastModified();
如果(filecatch.length()>=10485760 | | diff>10*24*60*60*1000){
System.out.println(“重命名完成”+filecatch.getName());
Path sourceFilePath=Path.get(filecatch.toURI());
Path targetFilePath=targetDirPath.resolve(filecatch.getName());
move(sourceFilePath、targetFilePath);
}
}
//如果目录不再可访问,请重置密钥并从集合中删除
布尔有效值=key.reset();
如果(!有效){
键。移除(键);
//所有目录都无法访问
if(key.isEmpty()){
打破
}
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<WatchKey, Path> keys;
private Path targetDirPath;
private Path sourceDirPath;
WatchDir(File sourceDir, File targetDir) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey, Path>();
this.sourceDirPath = Paths.get(sourceDir.toURI());
this.targetDirPath = Paths.get(targetDir.toURI());
WatchKey key = sourceDirPath.register(watcher, ENTRY_CREATE);
keys.put(key, sourceDirPath);
}
public static void main(String[] args) throws IOException {
// Directory that contain the files to be searched
File dir = new File("C:\\Users\\Mayank\\Desktop\\java princeton");
// new directory where files are to be moved
File des = new File("C:\\Users\\Mayank\\Desktop\\newDir");
if (!des.exists())
des.mkdir();
// register directory and process its events
new WatchDir(dir, des).processEvents();
}
/**
* Process all events for keys queued to the watcher
*
* @throws IOException
*/
private void processEvents() throws IOException {
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// Context for directory entry event is the file name of entry
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// here is a file or a folder modified in the folder
File fileCaught = child.toFile();
// here you can invoke the code that performs the test on the
// size file and that makes the file move
long diff = new Date().getTime() - fileCaught.lastModified();
if (fileCaught.length() >= 10485760 || diff > 10 * 24 * 60 * 60 * 1000) {
System.out.println("rename done for " + fileCaught.getName());
Path sourceFilePath = Paths.get(fileCaught.toURI());
Path targetFilePath = targetDirPath.resolve(fileCaught.getName());
Files.move(sourceFilePath, targetFilePath);
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
}