A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

    在我做的项目《基于在线学习的知识问答平台》中,有个模块涉及删除本地的资源文件。

         在这个模块中使用了java.io.File包,其中File类表示一个文件或者文件夹。

         在删除文件后,检查文件所在的文件夹是否为空,若为空,删除文件夹!

代码如下:



  • package test;







  • import java.io.File;







  • public class DeleteFile {







  •         public boolean deleteLocalFile(String address) {



  •                 File file = new File(address);



  •                 if (!file.exists()) {



  •                         System.out.println("删除失败,文件不存在!");



  •                         return false;



  •                 } else if (file.isFile()) {



  •                         if (file.delete()) {



  •                                 System.out.println("删除文件成功!");



  •                                 deleteDirectory(address);



  •                                 return true;



  •                         } else {



  •                                 System.out.println("删除文件失败!");



  •                                 return false;



  •                         }



  •                 } else {



  •                         System.out.println("Not a file!");



  •                         return false;



  •                 }



  •         }







  •         /**



  •          * 当目录为空时,删除目录



  •          */



  •         private void deleteDirectory(String address) {



  •                 // 获取文件所在的目录名称



  •                 address = address.substring(0, address.lastIndexOf('/') + 1);



  •                 File dir = new File(address);







  •                 // 删除空目录



  •                 String[] dirList = dir.list();



  •                 if (dirList == null) {



  •                         System.out.println("文件夹不存在");



  •                 } else if (dir.list().length > 0) {



  •                         System.out.println("这不是一个空目录,不能删除!");



  •                 } else if (dir.delete()) {



  •                         System.out.println("删除空目录成功!");



  •                 } else {



  •                         System.out.println("删除空目录失败");



  •                 }



  •         }







  •         public static void main(String[] args) throws Exception {



  •                 DeleteFile df = new DeleteFile();



  •                 String string = "C:/Users/lenovo/Desktop/test/test.txt";



  •                 df.deleteLocalFile(string);



  •         }







  • }


运行结果如下:


5 个回复

倒序浏览
优秀,奈斯
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马