Kerem
Kerem

Reputation: 715

How to recover Files delted with File.delete() method in java in Mac

I was writing a little java tool on my Mac to delete duplicate files like file[1].jpg It did work. After that I wanted to modify it quickly so that Files like file(1).png are deleted as well. I made a little mistake in my Regex and made a second mistake trusting myself and thinking nooo I don't need to test it. Now my Desktop has no files left.

Does java delete just the pointer to the Files or does it move the files somewhere so that I can recover the deleted files? They are not in the Trash. Is there some way to recover these files?

import java.util.regex.*;
import java.util.List;
import java.util.ArrayList;

public class DuplicateFilesDelter{
    public static void main(String [] args){
        if(args.length!=0){
            final File folder = new File(args[0]);
            List<File> filesToDelete = new ArrayList<File>();
            if(folder.isDirectory()&& folder.exists()){
                try{
                    File[] files = folder.listFiles();
                    int duplicates = 0;

                    for(File file : files){
                        String name = file.getName();
                        if(Pattern.matches(".*\\[[1-9]\\].*",name)|| Pattern.matches(".*([1-9]).*",name)){
                            filesToDelete.add(file);
                            duplicates++;
                        }
                    }
                    System.out.println("Deleting " +  duplicates + " duplicates from " + files.length);
                    int deleted = 0;
                    for(File f : filesToDelete){
                       try{
                           System.out.println("Delting " + f.getName() );
                            f.delete();
                            deleted++;
                        }catch(Exception e){} 
                    }
                    files = folder.listFiles();
                    System.out.println("Deleted " + deleted + " Files from " + filesToDelete.size());
                    System.out.println(files.length + " Files left");

        }catch(Exception e){
            System.err.println(e.getMessage());
        }
            }else{
                System.out.println( args[0] + "is Directory : " + folder.isDirectory());
                System.out.println( args[0] + "exists : " + folder.exists());
            }
        }
    }
}

Upvotes: 0

Views: 238

Answers (1)

Stephen C
Stephen C

Reputation: 719336

Does Java delete just the pointer to the Files or does it move the files somewhere so that I can recover the deleted files?

Java tells the operating system to delete the file on MacOS / Linux / UNIX by making an unlink syscall.

They are not in the Trash. Is there some way to recover these files?

Not in Java. You might be able to recover them with a file recovery tool.

Upvotes: 2

Related Questions