tags:

views:

1110

answers:

3

In java, does file.delete() return true or false where File file refers to a non-existent file?

I realize this is kind of a basic question, and easy to very through test, but I'm getting strange results and would appreciate confirmation.

A: 

The official javadoc:

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Returns:
    true if and only if the file or directory is successfully deleted; false otherwise 
Throws:
    SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

so, false.

Steve B.
+2  A: 

Doesn't that result in a FileNotFoundException?

EDIT:

Indeed it does result in false:

import java.io.File;

public class FileDoesNotExistTest {


  public static void main( String[] args ) {
    final boolean result = new File( "test" ).delete();
    System.out.println( "result: |" + result + "|" );
  }
}

prints false

dhiller
+4  A: 

From http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete():

Returns: true if and only if the file or directory is successfully deleted; false otherwise

Therefore, it should return false for a non-existent file. The following test confirms this:

import java.io.File;

public class FileTest
{
    public static void main(String[] args)
    {
        File file = new File("non-existent file");

        boolean result = file.delete();
        System.out.println(result);
    }
}

Compiling and running this code yields false.

Adam Rosenfield