import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
/**
* Class used to scan a given folder recursively to look for all empty folders. *
* @author gsolano
*
*/
public class DirEmptyFolder {
protected List<String> emptyFoldersList; // It will store all the empty folder paths.
public DirEmptyFolder() {
// Initializes the list.
emptyFoldersList = new LinkedList<String>();
}
public void scan(String rootDirPath) {
File sourceDir = new File(rootDirPath);
if(sourceDir.exists() && sourceDir.isDirectory()) {
emptyFoldersList.clear();
/*The real action: scan recursively.*/
scanRecursively(sourceDir);
System.out.println("Found " + emptyFoldersList.size() + " empty folders");
if(emptyFoldersList.size() > 0) {
System.out.println("Saving list...");
writeFilesToDisk("empty_folders_list.txt", emptyFoldersList);
System.out.println("Finished!");
}
} else {
System.out.println("Directory does not exist!");
}
}
/**
* Recursive method to find empty folders.
* @param sourceDir
*/
private void scanRecursively(File sourceDir) {
// List files and directories in the first level.
File[] listOfFiles = sourceDir.listFiles();
if (listOfFiles != null) {
for(int i=0; i < listOfFiles.length; i++) {
if(listOfFiles[i].isDirectory()) { // Only cares about directories.
if(listOfFiles[i].listFiles().length == 0) { // The directory has anything inside?
// Let's store the path and put it on screen.
emptyFoldersList.add(listOfFiles[i].getAbsolutePath());
System.out.println(listOfFiles[i].getAbsolutePath());
}
else {
// It's a directory but is not empty. Let's do the recursive call!
scanRecursively(listOfFiles[i]);
}
}
}
}
}
/**
* Saves the list in disk.
* @param filePath
* @param lines
*/
private void writeFilesToDisk(String filePath, List<String> lines) {
try{
FileWriter fstream = new FileWriter(filePath);
BufferedWriter out = new BufferedWriter(fstream);
for (String line : lines) {
out.write(line + "\n");
}
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
DirEmptyFolder dirEmptyFolder = new DirEmptyFolder();
dirEmptyFolder.scan(args[0]);
}
}
Salida (usando como entrada: "c:\documents and settings\gsolano\My Documents"):
...
c:\documents and settings\gsolano\My Documents\My Meetings
c:\documents and settings\gsolano\My Documents\New Folder
c:\documents and settings\gsolano\My Documents\videos
Found 43 empty folders
Saving list...
Finished!
No hay comentarios:
Publicar un comentario