使用在Files包中定义的Java.nio.file.files.deleteifexists (pathp )方法。 此方法删除文件(如果存在)。 只有当目录不为空时,路径中的目录也会被删除。
语法:
publicstaticbooleandeleteifexists (路径) throws IOException
参数: path -要删除的文件的路径
后退:如果方法删除了文件,则为true; 否则我要回false。
如果由于文件不存在而无法删除,则为false。
慢速:
DirectoryNotEmptyException -文件位于目录和
目录不为空,无法删除
(可选的特定例外)
发生ioexception-I/o错误时
//javaprogramtodemonstratedeleteusingfilesclass
import java.io.IOException;
import java.nio.file.*;
公共类测试
{
publicstaticvoidmain (字符串[ ] args ) )。
{
特里
{
files.deleteifexists (paths.get (c : (users\ mayank\ desktop
445.txt ' );
}
catch(nosuchfileexceptione ) )。
{
system.out.println (nosuchfile/directory exists );
}
目录不连续(catch ) )。
{
system.out.println (directoryisnotempty.';
}
catch(ioexceptione ) )。
{
system.out.println (' invalid permissions.';
}
system.out.println (deletion successful.);
}
}
输出:
deletion success风格。