X
Xyz1
Gast
Ihr kennt es doch wenn man im Explorer Eigenschaften eines Ordners öffnet, sieht man die darin enthaltenen Dateien und Größen. Etwas ähnliches wollte ich jetzt auch programmieren. Pro Ordner sollen die Anzahl der Dateien für alle Unterordner und die Größe ausgegeben werden.
Wenn die Ordnerstruktur so ist
foo/bar/baz/
und ich es für bar aufrufe ist die Ausgabe richtig, aber für foo falsch:
Wenn die Ordnerstruktur so ist
foo/bar/baz/
und ich es für bar aufrufe ist die Ausgabe richtig, aber für foo falsch:
Java:
public class Main extends SimpleFileVisitor<Path> {
HashMap<Path, Integer> cardinals = new HashMap<Path, Integer>();
HashMap<Path, Long> sizes = new HashMap<Path, Long>();
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!cardinals.containsKey(dir)) {
cardinals.put(dir, 0);
sizes.put(dir, 0L);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path p = file.getParent();
while (p != null && cardinals.containsKey(p)) {
cardinals.put(p, cardinals.get(p) + 1);
sizes.put(p, sizes.get(p) + file.toFile().length());
p = p.getParent();
}
return FileVisitResult.CONTINUE;
}
// If there is some error accessing
// the file, let the user know.
// If you don't override this method
// and an error occurs, an IOException
// is thrown.
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
return FileVisitResult.CONTINUE;
}
public static void main(String[] args) throws IOException {
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
j.showOpenDialog(null);
Main m = new Main();
Files.walkFileTree(j.getSelectedFile().toPath(), m);
ArrayList<CarsAndSizes> cas = new ArrayList<CarsAndSizes>(m.cardinals.size());
for (Entry<Path, Integer> e1 : m.cardinals.entrySet()) {
CarsAndSizes c = new CarsAndSizes();
c.p = e1.getKey();
c.car = e1.getValue();
c.size = m.sizes.get(e1.getKey());
cas.add(c);
}
Collections.sort(cas);
for (CarsAndSizes c : cas) {
System.out.println(c.p + " \t " + c.car + " \t " + c.size);
}
}
}
class CarsAndSizes implements Comparable<CarsAndSizes> {
Path p;
int car;
long size;
@Override
public int compareTo(CarsAndSizes o) {
if (car == o.car) {
if (size == o.size)
return p.compareTo(o.p);
else
return Long.compare(o.size, size);
}
return Integer.compare(o.car, car);
}
}