在此示例中,我们将展示如何使用File
类的delete()
方法删除文件或目录。 如果文件或目录已成功删除,则delete()
方法返回true
; 否则返回false
。
下面是File.delete()
的一个例子。
文件:DeleteFileDirectoryExample.java –
package com.yiibai.tutorial.io; import java.io.File; /** * @author yiibai * DeleteFileDirectoryExample.java * Nov 2, 2016 */ public class DeleteFileDirectoryExample { public static void main(String[] args) { /*Delete single file*/ System.out.println("-------------Deleting single file--------------"); File file=new File("test.txt"); if(file.exists()){ if(file.delete()){ System.out.println("File deleted successfully"); }else{ System.out.println("Fail to delete file"); } } System.out.println("/n-------------Deleting multiple files--------------"); /*Delete all files in directory*/ File folder=new File("folder"); if(folder.exists() && folder.isDirectory()){ for (File f : folder.listFiles()) { if(f.delete()){ System.out.println("'"+f.getName()+"' deleted successfully"); }else{ System.out.println("Fail to delete '"+f.getName()+"'"); } } } /*Delete folder*/ System.out.println("/n-------------Deleting folder--------------"); if(folder.exists() && folder.isDirectory()){ if(folder.delete()){ System.out.println("Folder deleted successfully"); }else{ System.out.println("Fail to delete folder"); } } } }
执行上面示例代码,得到以下结果:
-------------Deleting single file-------------- File deleted successfully -------------Deleting multiple files-------------- 'test.txt' deleted successfully 'test2.txt' deleted successfully 'test3.txt' deleted successfully 'test4.txt' deleted successfully 'test5.txt' deleted successfully 'test6.txt' deleted successfully 'test7.txt' deleted successfully -------------Deleting folder-------------- Folder deleted successfully
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264126.html