Java編程迭代地刪除文件夾及其下的所有文件實(shí)例
本文研究的是Java編程迭代地刪除文件實(shí)例,具體實(shí)現(xiàn)代碼如下。
實(shí)例代碼:
public static void main(String[] args) { String filePath = "c:" + File.separator +"b"; File file = new File(filePath); if (file.exists()) { if (file.isFile()) { deleteFile(filePath); } else { deleteDirectory(filePath); } } else { System.err.println("指定的目錄或者文件不存在!"); } } //刪除單個文件或空的文件夾 public static boolean deleteFile(String filePath) { File file = new File(filePath); //如果文件路徑對應(yīng)的文件存在,并且是一個文件,則直接刪除 if (file.exists() && file.isFile()) { if (file.delete()) { System.err.println("文件" + filePath + "刪除成功!"); return true; } else { System.err.println("文件" + filePath + "刪除失??!"); return false; } } else { System.err.println("文件" + filePath + "不存在!"); return false; } } //刪除文件夾及里面的文件 public static boolean deleteDirectory (String dir) { if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); //如果dir對應(yīng)的問件不存在,或者不是一個目錄,則退出 if (!dirFile.exists() || !dirFile.isDirectory()) { System.err.println("文件夾" + dir + "不存在!"); return false; } boolean flag = true; //刪除問價(jià)夾中的所有文件包括子目錄 File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { //刪除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } else { deleteDirectory(files[i].getAbsolutePath()); } } //刪除當(dāng)前目錄 if (dirFile.delete()) { System.err.println("目錄" + dir + "刪除成功!"); return true; } else { return false; } }
總結(jié)
以上就是本文關(guān)于Java編程迭代地刪除文件夾及其下的所有文件實(shí)例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
Python實(shí)現(xiàn)爬蟲設(shè)置代理IP和偽裝成瀏覽器的方法分享
今天小編就為大家分享一篇Python實(shí)現(xiàn)爬蟲設(shè)置代理IP和偽裝成瀏覽器的方法分享,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05Python?matplotlib繪圖時(shí)指定圖像大小及放大圖像詳解
Matplotlib是一個面向?qū)ο蟮睦L圖庫,我們繪制的圖像中,每條曲線,每個邊框等等都對應(yīng)一個對象,下面這篇文章主要給大家介紹了關(guān)于Python?matplotlib繪圖時(shí)指定圖像大小及放大圖像的相關(guān)資料,需要的朋友可以參考下2022-05-05pytorch 實(shí)現(xiàn)模型不同層設(shè)置不同的學(xué)習(xí)率方式
今天小編就為大家分享一篇pytorch 實(shí)現(xiàn)模型不同層設(shè)置不同的學(xué)習(xí)率方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法詳解
這篇文章主要介紹了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的方法,較為詳細(xì)的分析了VPS CENTOS 上配置python,mysql,nginx,uwsgi,django的具體步驟、相關(guān)命令與操作注意事項(xiàng),需要的朋友可以參考下2019-07-07