我使用监视服务来监视该文件夹,并且我编写了用于复制文件的代码。它不起作用。
这是我的代码
import java.util.HashMap;
import java.util.Map;
import java.nio.file.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HiddenProject {
public static void main(String[] args) {
// TODO Auto-generated method stub
try (WatchService Service = FileSystems.getDefault().newWatchService()){
Map<WatchKey, Path> KeyMap = new HashMap<>();
Path path = Paths.get("C:\\Users\\Pranu\\Downloads");
KeyMap.put(path.register(Service,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY),
path);
WatchKey watchkey;
do {
watchkey = Service.take();
Path eventDir = KeyMap.get(watchkey);
for (WatchEvent<?> event : watchkey.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path eventPath = (Path)event.context();
System.out.println(eventDir + ":" + kind + " :" + eventPath);
}
} while (watchkey.reset());
} catch (Exception e) {
///TODO: handle Exception
}
}
{
InputStream inStream = null;
OutputStream outStream = null;
try {
File act1 = new File("C:\\Users\\Praveen\\Downloads\\");
File act2 = new File("C:\\files\\");
inStream = new FileInputStream(act1);
outStream = new FileOutputStream(act2);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
//act1.delete();
System.out.println("File is copied successful!");
} catch(IOException e) {
e.printStackTrace();
}
}
}