我想在使用Java进入该文件夹时从文件夹中复制文件

时间:2016-10-31 13:27:54

标签: java watchservice

  1. 我希望在下载完成后将文件从我的下载文件夹(主要是文本和一些文件夹)复制到某个特定文件夹。
  2. 我想生成一个文本文件,显示有关下载/创建文件的信息。
  3. 我使用监视服务来监视该文件夹,并且我编写了用于复制文件的代码。它不起作用。

    这是我的代码

    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();
            }
         }
    }
    

0 个答案:

没有答案