Discover the size of a directory

2

I would like to know if it would be possible to find the size of a directory in JAVA .

I have a cache folder on my system and I would like to make a function whenever this folder exceeds a predefined size I could do a cleanup on it, however I do not know how to see the specific directory size! >

I have already looked in various forums and found no practical example that would get me this doubt.

    
asked by anonymous 08.12.2015 / 02:11

1 answer

3

The directory size is and will always be 0, because the directories are just shells!

Test this function, it is not my own, but it works until legal!

import java.io.*;  

class TamanhoAproximadoDiretorio {  
    /** 
     * Percorre um diretório e soma os tamanhos dos arquivos. 
     * @param dir Um diretório.  
     * @return A soma dos tamanhos dos arquivos no diretório e subdiretórios, em bytes. 
     */  
    long tamanho (File dir) {  
        long ret = 0;  
        for (File f : dir.listFiles()) {  
            if (f.isDirectory()) {  
                ret += tamanho (f);  
            } else {  
                ret += f.length();  
            }  
        }  
        return ret;  
    }  

  public static void main(String[] args) {  
    if (args.length < 1) {  
        System.out.println ("Sintaxe: java -cp . TamanhoAproximado diretorio");  
        System.exit (1);  
    }  
    TamanhoAproximadoDiretorio t = new TamanhoAproximadoDiretorio();  
    File dir = new File (args[0]);  
    // Aqui estou mostrando o tamanho usando a definição do Windows (1 MB = 1024 KB = 1.048.576 bytes)  
    System.out.printf ("O diretório %s (e seus subdiretórios) ocupa %.3f megabytes%n", args[0], t.tamanho (dir) / 1048576.0);  
}  

}

Another one that can also help you, find out which fits your conditions:

public static int getFolderSize(String path)  {     
File folder = new File(path);     
int size = 0;     
if (folder.isDirectory()) {     
    String[] dirList = folder.list();     
    if (dirList != null) {     
        for (int i = 0; i < dirList.length; i++) {     
            String fileName = dirList[i];     
            File f = new File(path, fileName);     
            if (f.isDirectory()) {     
                String filePath = f.getPath();     
                size += getFolderSize(filePath);     
                continue;     
            }     
            size += f.length();     
        }     
    }     
}     
return size; 
    
08.12.2015 / 02:25