对于不存在的文件,file.delete()是返回true还是false?

时间:2008-11-21 05:14:43

标签: java file

在java中,file.delete()返回truefalse File file是否指向不存在的文件?

我意识到这是一个基本问题,很容易通过测试,但我得到了奇怪的结果,并希望得到确认。

3 个答案:

答案 0 :(得分:8)

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

返回:当且仅当文件或目录被成功删除时才返回true;否则是假的

因此,对于不存在的文件,它应该返回false。以下测试证实了这一点:

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);
    }
}

编译并运行此代码会产生错误。

答案 1 :(得分:4)

这不会导致FileNotFoundException吗?

编辑:

确实会导致错误:

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 + "|" );
  }
}

打印false

答案 2 :(得分:2)

官方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

所以,错误。