Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does file.delete() return true or false for non-existent file?

Tags:

java

file

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.

like image 579
carrier Avatar asked Nov 21 '08 05:11

carrier


2 Answers

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.

like image 99
Adam Rosenfield Avatar answered Oct 28 '22 23:10

Adam Rosenfield


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

like image 34
Daniel Hiller Avatar answered Oct 28 '22 22:10

Daniel Hiller