- Inside your TimerTask, use
File#listFiles()
(possibly with theFilenameFilter
parameter, if that suits your needs) to get a list of files in the source directory. - Iterate through the returned Files looking for the first item that is not a directory (assuming that you want to move only normal files).
- Move that file.
- 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.
How to move files one by one using java
Frage
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
Lösung
Andere Tipps
- Start a
Timer
that fires every 60 seconds. - In the constructor of the
Timer
, useDirectoryStream<Path>
to get all the files in a directory. This is done using the static method ofFiles
class in thenio
package. - Then, use
Files.move()
in theTimer
to move the files one by one. - 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
.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow