Java 对于不存在的文件,file.delete()是否返回true或false?
在java中,Java 对于不存在的文件,file.delete()是否返回true或false?,java,file,Java,File,在java中,file.delete()是否返回true或false其中file文件指的是不存在的文件 我意识到这是一个基本问题,很容易通过测试,但我得到了奇怪的结果,希望得到确认。官方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
file.delete()
是否返回true
或false
其中file文件
指的是不存在的文件
我意识到这是一个基本问题,很容易通过测试,但我得到了奇怪的结果,希望得到确认。官方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
所以,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
:
当且仅当成功删除文件或目录时返回: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);
}
}
编译并运行此代码会产生false