在java中,是否file.delete()
返回true
或false
其中File file
是指一个不存在的文件?对于不存在的文件,file.delete()是否返回true或false?
我意识到这是一个基本的问题,很容易通过测试,但我得到奇怪的结果,并希望确认。
在java中,是否file.delete()
返回true
或false
其中File file
是指一个不存在的文件?对于不存在的文件,file.delete()是否返回true或false?
我意识到这是一个基本的问题,很容易通过测试,但我得到奇怪的结果,并希望确认。
这不会导致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
官方的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
所以,假的。
从http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete():
返回:当且仅当文件或目录成功删除;否则为假
因此,它应该为不存在的文件返回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);
}
}
编译并运行此代码会产生错误。