Question

i know how to send all files from one directory to another in one time. but how can i want send files (.txt) from one directory to another one by one with a delay of 60s.

import java.io.File;

public class MoveFilesJavaExample {

    public static void main(String[] args) {
        try {

            File oldFile = new File("C:\\source\\File.txt");

            if (oldFile.renameTo(new File("C:\\destination"+ oldFile.getName()))) {
                System.out.println("The file was moved successfully to the new folder");
            } else {
                System.out.println("The File was not moved.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I can use the following code but it only do the same job every 5s.

import java.util.Timer;
import java.util.TimerTask;

public class UtilTimerDemo {
  public static void main(String[] argv) throws Exception {
    int delay = 5000; // delay for 5 sec.
    int period = 1000; // repeat every sec.
    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
        System.out.println("doing"); 
      }
    }, delay, period);
  }
}

Thank you

Was it helpful?

Solution

  1. Inside your TimerTask, use File#listFiles() (possibly with the FilenameFilter parameter, if that suits your needs) to get a list of files in the source directory.
  2. Iterate through the returned Files looking for the first item that is not a directory (assuming that you want to move only normal files).
  3. Move that file.
  4. Optionally (depending on your requirements) if you got to the end of the array of returned Files and didn't find any non-directories, then stop the TimerTask.

OTHER TIPS

  1. Start a Timer that fires every 60 seconds.
  2. In the constructor of the Timer, use DirectoryStream<Path> to get all the files in a directory. This is done using the static method of Files class in the nio package.
  3. Then, use Files.move() in the Timer to move the files one by one.
  4. Stop the Timer when you have iterated over all the files in the stream.

DirectoryStream can be globbed, thus allowing you to filter the files that you want. You can either write simple extensions or complex RegEx to decide what files are returned in your DirectoryStream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top