Created
August 8, 2018 06:00
-
-
Save runnerdave/e56a67217d2bc2c5c3b262a81849c0a6 to your computer and use it in GitHub Desktop.
simple recursive app to recursively map a local directory as well as return its total size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.HashMap; | |
class FileRecursor { | |
private static HashMap<String, File> filesMap = new HashMap(); | |
private static long totalSize = 0; | |
public static void main(String[] args) { | |
System.out.println("==List all files in current directory and total size they occupy=="); | |
File folder = new File("."); | |
System.out.println(statFiles(folder) / (1024) + " KB"); | |
System.out.println(filesMap); | |
} | |
/** | |
* Returns the total size of a directory | |
*/ | |
public static long statFiles(File dir) { | |
try { | |
File[] listOfFiles = dir.listFiles(); | |
for (int i = 0; i < listOfFiles.length; i++) { | |
File f = listOfFiles[i]; | |
totalSize += f.length(); | |
if (f.isDirectory() && !filesMap.containsKey(f.getPath())) { | |
filesMap.put(f.getPath(), f); | |
String isSymbolic = ""; | |
if (isSymlink(f)) { | |
isSymbolic = "(symlink)"; | |
} | |
System.out.println("===Directory contents for " + f + isSymbolic); | |
statFiles(f); | |
} else { | |
System.out.println(" " + f.getName()); | |
} | |
} | |
} catch (Exception e) { | |
System.out.println(e.getMessage()); | |
} | |
return totalSize; | |
} | |
public static boolean isSymlink(File file) throws IOException { | |
if (file == null) | |
throw new NullPointerException("File must not be null"); | |
File canon; | |
if (file.getParent() == null) { | |
canon = file; | |
} else { | |
File canonDir = file.getParentFile().getCanonicalFile(); | |
canon = new File(canonDir, file.getName()); | |
} | |
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment