使用Files包中定义的java.nio.file.files.deleteifexists(Path p)方法:此方法删除文件(如果存在)。仅当目录不为空时,它还会删除路径中提到的目录。
句法:
public static boolean deleteIfExists(Path path)throws IOException
参数: path - 要删除的文件的路径
返回:如果该方法删除了该文件,则返回 true;否则返回 false。
如果由于文件不存在而无法删除,则为false。
抛出:
DirectoryNotEmptyException - 如果文件是目录和
否则无法删除,因为该目录不为空
(可选特定例外)
IOException - 如果发生I / O错误
// Java program to demonstrate delete using Files class
import java.io.IOException;
import java.nio.file.*;
public class Test
{
public static void main(String[] args)
{
try
{
Files.deleteIfExists(Paths.get("C:\\Users\\Mayank\\Desktop\\
445.txt"));
}
catch(NoSuchFileException e)
{
System.out.println("No such file/directory exists");
}
catch(DirectoryNotEmptyException e)
{
System.out.println("Directory is not empty.");
}
catch(IOException e)
{
System.out.println("Invalid permissions.");
}
System.out.println("Deletion successful.");
}
}
输出:
Deletion successful.