Java在服務器下刪除文件、刪除目錄及目錄下所有文件失敗(file.delete() --> false)


刪除文件或者目錄失敗可能有兩個原因:

1. 流沒有關閉導致文件被占用,從而刪除失敗

 

public String getfilesize(String path,String filename) throws IOException {
    String pathString=path+"\\"+filename;
    f=new File(pathString);
    FileInputStream fis=new FileInputStream(f);
    String time=String.valueOf(((double)fis.available() / 1024));
    fis.close();//當時這里沒有關閉
    return time.substring(0, time.indexOf(".")+2)+"K";
 }

 

2. File.delete()用於刪除“某個文件或者空目錄”!

  重點是刪除的對象是文件和空目錄,非空目錄要進行遞歸刪除

/**
 * @ProjectName: test
 * @Package: com.test.utils
 * @ClassName: DeleteDirectory
 * @Author: ***
 * @Description:Java中刪除文件、刪除目錄及目錄下所有文件
 * @Date: 2021/1/17 16:15
 * @Version: 1.0
 */
public class DeleteDirectory {

    /**
     * 刪除空目錄
     * @param dir 將要刪除的目錄路徑
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     * @param dir 將要刪除的文件目錄
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //遞歸刪除目錄中的子目錄下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時為空,可以刪除
        return dir.delete();
    }

 /**
     *測試
     */
    public static void main(String[] args) {
        doDeleteEmptyDir("new_dir1");
        String newDir2 = "new_dir2";
        boolean success = deleteDir(new File(newDir2));
        if (success) {
            System.out.println("Successfully deleted populated directory: " + newDir2);
        } else {
            System.out.println("Failed to delete populated directory: " + newDir2);
        }     
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM