用Java显示已删除的文件

用Java显示已删除的文件,java,Java,我必须写一个Java程序,显示从计算机和回收站删除的文件。只显示已删除的文件,而不是恢复它们。 请问,我该怎么办 谢谢。公共课堂收听目录{ public class Listen_Directory { private final WatchService watcher ; private final Map<WatchKey,Path> keys; private final boolean recursive; private boolean trace = false; p

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

谢谢。

公共课堂收听目录{
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 ;        
}
私人最终观察者服务观察者; 私有最终映射密钥; 私有最终布尔递归; 私有布尔跟踪=false; 私有静态PrintWriter writeEvent=null; 静态接口interf=新接口(); //私有静态列表listDeletedFiles=new ArrayList(); @抑制警告(“未选中”) 静态WatchEvent强制转换(WatchEvent事件){ 返回(WatchEvent)事件; } /** *向WatchService注册给定目录 */ 私有无效寄存器(路径目录)引发IOException{ WatchKey key=dir.register(观察者、条目创建、条目删除、条目修改); 如果(跟踪){ 路径prev=keys.get(key); if(prev==null){ System.out.format(“寄存器:%s\n”,dir); }否则{ 如果(!dir.equals(prev)){ System.out.format(“更新:%s->%s\n”,上一个,目录); } } } keys.put(key,dir); } /** *将给定目录及其所有子目录注册到 *值班服务。 */ 私有void registerAll(最终路径开始)引发IOException{ //注册目录和子目录 试一试{ walkFileTree(开始,新的SimpleFileVisitor(){ @凌驾 公共文件VisitResult preVisitDirectory(路径目录, 基本文件属性(属性属性) 抛出IOException { 注册主任; 返回FileVisitResult.CONTINUE; } }); }捕获(AccessDeniedException exc){ }捕获(FileSystemException ex){ } } /** *创建WatchService并注册给定目录 */ Listen_目录(路径目录,布尔递归)引发IOException{ this.watcher=FileSystems.getDefault().newWatchService(); this.keys=new HashMap(); this.recursive=递归; if(递归){ 系统输出格式(“扫描%s…\n”,目录); 注册主任; System.out.println(“完成”+dir); }否则{ 注册主任; } //在初始注册后启用跟踪 this.trace=true; } /** *处理排队给观察者的密钥的所有事件 */ void processEvents(){ 对于(;;){ //等待钥匙发出信号 监视键; 试一试{ key=watcher.take(); }捕捉(中断异常x){ 返回; } Path dir=keys.get(key); if(dir==null){ System.err.println(“未识别WatchKey!!”; 继续; } for(WatchEvent事件:key.pollEvents()){ WatchEvent.Kind-Kind=event.Kind(); System.out.format(“%s:\n”,event.kind().name()); //TBD-提供如何处理溢出事件的示例 //目录条目事件的上下文是条目的文件名 WatchEvent ev=铸造(事件); 路径名=ev.context(); 路径子项=目录解析(名称); //打印输出事件 System.out.format(“%s:%s\n”,event.kind().name(),child); createDataLink(); 字符串fiche=checkIfIsInRecycleBin(child.toString()); writeEvent.append(fiche+“\n”); writeEvent.flush(); interf.jtextraepath.append(fiche+“\n”); 如果(种类==溢出){ 继续; } //若创建了目录,并递归地监视,则 //注册它及其子目录 if(递归/*&&(种类==条目_创建)*/){ 试一试{ if(Files.isDirectory(子目录、NOFOLLOW_链接)){ 登记处(儿童); } }捕获(IOX异常){ //忽略以保持样本的可读性 } } } //如果目录不再可访问,请重置密钥并从集合中删除 布尔有效值=key.reset(); 如果(!有效){ 键。移除(键); //所有目录都无法访问 if(key.isEmpty()){ 打破 } } } } 静态void用法(){ System.err.println(“用法:javawatchdir[-r]dir”); 系统退出(-1); } 公共静态void main(字符串[]args)引发IOException{ 干涉设置可见(真); 干涉setLocationRelativeTo(空); File[]listfichiers=File.listRoots(); 对于(文件leFichier:listeFichiers){ 字符串leChemin=leFichier.getAbsolutePath(); //如果((!leChemin.equals(“F:\\”)和((!leChemin.equals(“D:\\”))的 //&&(!leChemin.equals(“E:\\”){ 管理线程目录 =新的管理线程目录(leChemin); gestNotif.start(); //} } //writeEvent.close(); } 私有void createDataLink(){ 试一试{ 字符串userLogged=System.getProperty(“user.name”); File dir=新文件(“c:/Users/”+userLogged+“/NotesDeletedFiles”); 如果(!dir.exists()){ System.out.println(dir.mkdir()); } 文件数据文件=新文件(“c:/Users” +“/”+userLogged+“/NotesDeletedFiles/Data.in”); 如果(!dataFile.exists()){ dataFile.createNewFile(); } writeEvent=新的PrintWriter(新的BufferedWriter)(新的FileWriter( “c:/Users/”+userLogged+“/NotesDeletedFiles/Data.in”,true)); }捕获(IOEX异常){ Logger.getLogger(Listen\u Directory.class.getName())。 日志(Level.SEVERE、null、ex); } } 私有字符串校验循环BIN(字符串链){ 字符串resu=链; 字符串选项卡[]=chaine.split(“\\”); 对于(int i=0;i 2){ 字符串ch=tab[i]; 如果(ch.startsWith(“$REC”)){ resu=“回收站”+
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);
    }
}