Java如何删除文件?别担心,Java提供了使用Java删除文件的方法进行文件处理。与任何操作系统中的正常删除操作相反, 使用java删除的文件将被永久删除, 而不会移动到垃圾回收站,所以删除文件要小心处理。
方法1:Java如何删除文件?以下是用于Java删除文件的方法
使用java.io.File.delete()函数:删除此抽象路径名表示的文件或目录。
语法如下:
public boolean delete()
Returns: true if and only if the file or
directory is successfully deleted; false otherwise
// Java program to delete a file
import java.io.*;
public class Test
{
public static void main(String[] args)
{
File file = new File( "C:\\Users\\Mayank\\Desktop\\1.txt" );
if (file.delete())
{
System.out.println( "File deleted successfully" );
}
else
{
System.out.println( "Failed to delete the file" );
}
}
}
输出如下:
File deleted successfully
方法2:Java如何删除文件?Java删除文件使用在文件包中定义的java.nio.file.files.deleteifexists(Path p)方法:
此方法删除文件(如果存在)。仅当目录不为空时, 它也会删除路径中提到的目录。
语法如下:
public static boolean deleteIfExists(Path path) throws IOException
Parameters: path - the path to the file to delete
Returns: true if the file was deleted by this method;
false if the file could not be deleted because it did not exist.
Throws:
DirectoryNotEmptyException - if the file is a directory and
could not otherwise be deleted because the directory is not empty
(optional specific exception)
IOException - if an I/O error occurs
// 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.
参考:
Java如何删除文件?以上就是Java删除文件的详细实现,其中要记住使用Java删除文件要小心,开发中可以先使用测试文件进行删除,然后再用于生产环境。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。