创建一个线程,监视某个目录,一旦目录里出现新的文件,就将文件转移到指定的目录里去。求方法,求代码,谢谢了

解决方案 »

  1.   

    思路:
    1.先创建一个线程(thread)
    2.线程负责查看指定目录
    3.判断  目录如果不为空说明出现新文件 
    4.出现新文件  实例化一个file对象  把文件存放到相应的目录
      

  2.   

    for example
    class MonitorThread extends Thread {
        String srcdir;
        String targetdir;
        boolean running = true;
        public MonitorThread(String srcdir, String targetdir) {
            this.srcdir = srcdir;
            this.targetdir = targetdir;
        }
        public void stop() {this.running = false;}    public void run() {
            File dir = new File(srcdir);
            while (running) {
                try {
                    if (!dir.isDirectory()) {
                        System.out.println("not directory");
                        return;
                    }
                    if (dir.listFiles().length() > 0) {
                        Process p = Runtime.getRuntime().exec("move /Y " + srcdir + "/*.* " + targetdir + "/.");
                        p.waitFor();
                    } else {
                        sleep(1000);
                    }                
                } catch (Exception e) {e.printStackTrace();}
            }
        }
    }
      

  3.   

    LZ是要判断新文件啊,那就第一次启动时把原来的文件保存到一个结合中    public void run() {
            File dir = new File(srcdir);
            if (!dir.isDirectory()) {
                System.out.println("not directory");
                return;
            }        Set<File> originalFiles = new HashSet<File>();
            for (File f : dir.listFiles()) {
                orignalFiles.add(f);
            }
            Set<File> newFiles = new HashSet<File>();
            while (running) {
                try {     
                    newFiles.clear();
                    for (File f : dir.listFiles()) {
                        if (!originalFiles.contains(f)) {
                            newFiles.add(f);
                        }
                    }           
                    if (newFiles.size() > 0) {
                        StringBuilder cmd = new StringBuilder("move /Y ");
                        for (File f : newFiles) {
                            cmd.append(f.getAbsoluteFile().getPath()).append(" ");
                        }
                        cmd.append(targetdir + "/.");                    Process p = Runtime.getRuntime().exec(cmd.toString());
                        p.waitFor();
                    } else {
                        sleep(1000);
                    }                
                } catch (Exception e) {e.printStackTrace();}
            }
        }
      

  4.   

    给你两个参考链接:
    http://download.oracle.com/javase/tutorial/essential/io/notification.html  (英文)
    http://xxing22657-yahoo-com-cn.iteye.com/blog/1054496    (中文)