Olá pessoal,
gostaria de uma ajuda no seguinte:
Tenho um trecho de código onde eu preciso verificar se um diretório está vazio. Ex:
C:\Diretorio\Subdiretorio
if(Subdiretorio está vazio){
//deletar o subdiretorio
}
Estou usando a classe File e está atendendo a algumas necessidades. Porém, não existe um método que verifique se o diretório está vazio, algo como isEmpty(). Eu tenho como verificar se um arquivo ou diretório existe através do exists(), mas esse não me serve. Eu preciso verificar se um determinado diretório está vazio ou se contém arquivo(s) ou subpasta(s).
Agradeço a atenção.
public static boolean isDiretorioVazio(String diretorio) {
File dir = new File(diretorio);
String[] children = dir.list();
if (children == null) {
// Diretorio nao existe ou nao eh um diretorio
return true;
} else {
if (children.length > 0) {
return false;
}
}
return false;
}
[quote]
public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory’s parent directory are not included in the result. Each string is a file name rather than a complete path.
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Retornos:
An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Excessões:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the directory [/quote]
Liste os arquivos desse diretório, com listFiles(). Não sei se ao listar ele mostra sempre as entradas “.” e “…” ou se ele retorna um array de comprimento zero.