用Java显示已删除的文件

时间:2016-08-16 17:15:32

标签: java

我必须编写一个Java程序,它显示从计算机和回收站中删除的文件。只显示已删除的文件,而不是恢复它们。 请问,我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:0)

public class Listen_Directory {

private final WatchService watcher ;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
private static PrintWriter writeEvent = null ;
static Interface interf = new Interface();
//private static List<String> listDeletedFiles = new ArrayList<>();



@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}



/**
 * Register the given directory with the WatchService
 */
private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher,ENTRY_CREATE,ENTRY_DELETE, ENTRY_MODIFY);

    if (trace) {
        Path prev = keys.get(key);
        if (prev == null) {
            System.out.format("register: %s\n", dir);
        } else {
            if (!dir.equals(prev)) {
                System.out.format("update: %s -> %s\n", prev, dir);
            }
        }
    }
    keys.put(key, dir);
}

/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService.
 */
private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    try  {
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, 
                BasicFileAttributes attrs)
            throws IOException
        {
            register(dir);
            return FileVisitResult.CONTINUE;
        }
    });
    } catch (AccessDeniedException exc){

    } catch (FileSystemException ex){

    }
}

/**
 * Creates a WatchService and registers the given directory
 */
Listen_Directory(Path dir, boolean recursive) throws IOException {

    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey,Path>();
    this.recursive = recursive;

    if (recursive) {
        System.out.format("Scanning %s ...\n", dir);
        registerAll(dir);
        System.out.println("Done_"+dir);
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}

/**
 * Process all events for keys queued to the watcher
 */
void processEvents() {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();

             System.out.format("%s: \n", event.kind().name());

            // TBD - provide example of how OVERFLOW event is handled


            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // print out event
            System.out.format("%s: %s\n", event.kind().name(), child);

            createDataLink();

            String fiche = checkIfIsInRecycleBin( child.toString());

            writeEvent.append(fiche+ "\n");
            writeEvent.flush();

            interf.jTextAreaPaths.append( fiche+"\n");

            if (kind == OVERFLOW) {
                continue;
            }
            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (recursive /*&& (kind == ENTRY_CREATE)*/) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                }
            }
        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

static void usage() {
    System.err.println("usage: java WatchDir [-r] dir");
    System.exit(-1);
}

public static void main(String[] args) throws IOException {


    interf.setVisible(true);
    interf.setLocationRelativeTo(null);

    File[] listeFichiers = File.listRoots();

    for( File leFichier : listeFichiers){
        String leChemin = leFichier.getAbsolutePath() ;

        //if ( ( !leChemin.equals("F:\\")) && ( !leChemin.equals("D:\\"))
          //      && ( !leChemin.equals("E:\\"))){
        Manage_Thread_Directories gestNotif 
                    = new Manage_Thread_Directories(leChemin);
        gestNotif.start();
        //}

    }
    //writeEvent.close();
}



private void createDataLink(){
    try {

        String userLogged = System.getProperty("user.name");


        File dir = new File("c:/Users/"+userLogged+"/NotesDeletedFiles");
        if( !dir.exists()){
            System.out.println(dir.mkdir());
        }

        File dataFile = new File("c:/Users"
                + "/"+userLogged+"/NotesDeletedFiles/Data.in");
        if (!dataFile.exists()){
            dataFile.createNewFile();
        }

        writeEvent = new PrintWriter(new BufferedWriter(new FileWriter(
                "c:/Users/"+userLogged+"/NotesDeletedFiles/Data.in", true)));


    } catch (IOException ex) {
        Logger.getLogger(Listen_Directory.class.getName()).
                log(Level.SEVERE, null, ex);
    }


}

private String checkIfIsInRecycleBin(String chaine) {
    String resu = chaine;
    String tab[] = chaine.split("\\\\");

    for(int i=0; i<tab.length; i++){
        if (tab[i].length() > 2){
            String ch = tab[i];
            if (ch.startsWith("$REC")){
                resu = "Recycle bin" + 
                        "\\"+tab[ tab.length -1 ] ;
                break ;
                //return resu ;
            }
        }


    }

    return resu ;        
}

}

public class Manage_Thread_Directories extends Thread {     private String cheminAcces =&#34;&#34 ;;

public Manage_Thread_Directories(String leChemin) {
    this.cheminAcces = leChemin ;
}

@Override
public void run() {



     String faire = "-r";
    if (cheminAcces.length() == 0 )
        usage();
    boolean recursive = false;

    if (faire.equals("-r")) {
        //if (cheminAcces.length() < 2)
          //  usage();
        recursive = true;

    }

    // register directory and process its events
    Path dir = Paths.get(cheminAcces);
    try {
        new Listen_Directory(dir, recursive).processEvents();

        //super.run(); 
    } catch (IOException ex) {
        Logger.getLogger(Manage_Thread_Directories.class.getName()).
                log(Level.SEVERE, null, ex);
    }
}

}