gpt4 book ai didi

监控目录的java程序

转载 作者:搜寻专家 更新时间:2023-10-31 20:17:32 24 4
gpt4 key购买 nike

我想创建一个 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()));

} }
}
}

最佳答案

watch 服务应符合您的需求:https://docs.oracle.com/javase/tutorial/essential/io/notification.html

以下是实现 watch 服务所需的基本步骤:

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

附带说明一下,您应该喜欢从 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() 也可能会失败。
此外,该方法在失败时可能会返回一个 boolean 值而不是异常。
这样可能很难猜到问题的根源并在代码中处理。

这是一个执行您的要求的简单类(它处理所有步骤,但不一定需要关闭 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;
}
}
}
}

}

关于监控目录的java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42750198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com