您如何反复检查文件夹并将文件夹中的任何新文件移动到 Java 中的另一个目录?

How can you repeatedly check a folder and move any new files in the folder to another directory in Java?

我正在 java 中编写一个程序,我想知道是否有一种方法可以重复检查文件夹中的任何新文件(大约每 30 秒一次)并将任何新文件移动到另一个文件夹文件夹。

我已经有了移动文件的工作代码,但在检查文件夹中的新文件时找不到任何东西。

我建议你使用 Timer

Timer timer = new Timer();
List<String> list = new List();
//repeat your timer
timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    //loop through the folder and get the names
    File folder = new File("your/path");
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        if(list.contains(listOfFiles[i].getName())
         {
             //already checked file
         }
      else
         {
             //new file add your move logic and add it to the list
             list.add(listOfFiles[i].getName());
         } 
      } 
    }
  }
}, 2*60*1000, 2*60*1000);

看看Java路径接口:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html

https://docs.oracle.com/javase/tutorial/essential/io/dirs.html

您可以使用像 Quartz 这样的调度程序来完成它,您可以在其中创建将由 java 执行的任务以实现此目标。

无论如何,我认为这不是一个很好的解决方案。使用脚本可以更轻松地完成此操作。例如,在 linux 中,您可以创建一个 file_scheduler.sh 脚本,列出文件夹中的文件并将它们移动到另一个文件夹中,并在每次需要时使用命令 crontab 执行此任务。

您可以查看 java.nio.file.WatchService 而不是使用重复计时器,它可以让您在目录中的文件被添加、修改或删除时收到通知。