我有一个要求,需要在Java中监视目录中文件的复制状态,并且文件会不断地放入该目录。 我计划使用Executor框架来查找单个文件的复制状态,并编写了下面的代码,但它的工作效果并不如预期,未完成复制的文件却提示复制已完成。
private boolean isFileCopied(String filePath) {
File file = new File(filePath);
Scanner scanner;
boolean isCopied = true;
while (true) {
try {
scanner = new Scanner(file);
isCopied = false;
} catch (FileNotFoundException e) {
System.out.println(filePath + " File is in copy State. ");
sleepFile();
}
if (isCopied == false) {
break;
}
}
System.out.println(filePath + " copy completed");
return isCopied;
}
private static void sleepFile() {
System.out.println("sleeping for 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
请有人帮我找到文件的确切状态,例如“复制进行中”或“复制完成”,并且如何监视每个文件的复制状态,如果有一堆大文件放在一个目录中。
我已经使用了Watcher API,但它没有解决我的问题。即使没有复制的文件也完成了,我也会得到复制完成的通知。以下是我的代码更改。
使用观察程序服务:
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
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;
public class FolderWatchDemo {
public static void main(String[] args) {
final Path outputWatchFolderPath = Paths.get("/outputFolder/");
final Path sourceFolderPath = Paths.get("/sourceFolder/");
try {
//Registering outputWatchFolderPath
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(outputWatchFolderPath.toString());
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
//copy files from inputfolder to o
for (final Path path: Files.newDirectoryStream(sourceFolderPath))
Files.copy(path, outputWatchFolderPath.resolve(path.getFileName()));
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>) event;
if (kind == ENTRY_CREATE) {
System.out.println("file got created !!");
}
if (kind == ENTRY_MODIFY) {
System.out.println("copying got completed !!");
}
if (kind == ENTRY_DELETE) {
System.out.println("file deleted successfully !!");
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
提前感谢你。
WatchService
呢? - Andy TurnerWatchService
的代码。 - Andy Turner