[英]java program to monitor a directory
我想創建一個程序來監視目錄 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:\\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()));
} }
}
}
手表服務應該符合您的需要: https : //docs.oracle.com/javase/tutorial/essential/io/notification.html
以下是實現手表服務所需的基本步驟:
作為旁注,您應該支持自 Java 7 以來可用的java.nio
包來移動文件。
renameTo()
有一些嚴重的限制(摘自 Javadoc):
此方法的行為的許多方面本質上是平台相關的:重命名操作可能無法將文件從一個文件系統移動到另一個文件系統,它可能不是原子的,並且如果具有目標抽象路徑名的文件可能不會成功已經存在。 應始終檢查返回值以確保重命名操作成功。
例如在 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<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;
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.