簡體   English   中英

在Java中獲取文件夾的大小會返回負數long

[英]Getting the size of a folder in Java returns negative long

我正在嘗試獲取目錄的長度(文件大小),並且已通過以下遞歸方法進行操作,只有在傳遞new File("C:\\\\Users\\\\UserName\\\\Desktop")作為參數。

static long totalLength = 0;

// Method to get the size of a folder and its contents
private static long getFolderSize(File folder){
    if(folder.isDirectory()){
        File[] contents = folder.listFiles();
        for(File current : contents){
            if(current.isDirectory()){
                totalLength = totalLength +getFolderSize(current);
            }
            totalLength = totalLength + current.length();
        }
    }
    return totalLength;
} 

但是,有趣的是,當我將某些文件夾傳遞給方法時,它們確實會返回預期的結果。 我只是不知道為什么:我已經對單個文件的長度進行了一些調試,但它們似乎都不是負數,但是有時我還是得到負數結果!

任何想法,將不勝感激! 提前致謝

您在isDirectory() if語句上缺少else {}塊。 如此一來,您將在目錄中調用File.length() ,該目錄根據文檔未指定。 它很可能返回負值。

關於File.length()文檔在這里: http : //docs.oracle.com/javase/6/docs/api/java/io/File.html#length()

您的代碼可能應該顯示為:

 if(current.isDirectory()) {
    totalLength = totalLength +getFolderSize(current, initial);
  } else {
    totalLength = totalLength + current.length();
  }

您為什么不使用已內置庫的已建立庫,例如:

其中也有測試來涵蓋這種情況。

我認為從樣式上看這更好:

    private static long getFolderSize(File f) {
        if(!f.isDirectory()) return f.length();
        long totalLength = 0;
        for (File current : f.listFiles()) {
            totalLength += getFolderSize(current);
        }
        return totalLength;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM