Java File.delete

Categories
j4va development j2se

Here we have another easy Java tutorial. You want to delete a file. Easy, right?

import java.io.File;

class j4vaDelete
{

        void deleteJohn() { 
                String filename="john.txt";
                
                File file = new File(filename);
                if(file.exists()){ file.delete(); }
         }

        // public 

        public static void main(String [] args)
        {
                j4vaDelete a = new j4vaDelete();
                a.deleteJohn();
        }

}

Well, it never is just that easy. What if you don't have permission to delete this file?

javac j4vaDelete.java
echo data > john.txt
chmod a-w .
java j4vaDelete

What do you expect the outcome to be? Deleted file? No. Runtime Exception? No. It does nothing. There are two ways to detect whether the file was actually deleted. The first is to check the return value. The second is after you delete a file, check whether it was deleted by checking the value of file.exists(). If that doesn't work you either have to throw an exception yourself, inform the user, or do nothing. Fun, eh? What is more fun is when you have a lot of code relying upon this deletion. What if the user accidentally uploaded a file they didn't want to display? You delete it and you say it was deleted but it doesn't actually delete.

Java's documentation of the File.delete method

The true lesson for today: always test whether what you need done gets done.