Find out the size of a directory

Asked

Viewed 553 times

2

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

I have a cache folder on my system and I would like to do a function forever that this folder exceeds a predefined size I could do a cleaning in it, however I do not know how to see the size of the directory in specific!

I have searched in several forums and found no practical example that would remove this doubt.

  • 1

    I have removed greetings and thanks as directed here: https://pt.meta.stackoverflow.com/questions/846/greetings-thanks

1 answer

3


Directory size is and always will be 0, because directories are just reservoirs!

Test this function, it’s not my fault, but it works until it’s 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 that can also help you, find out which one 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; 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.