0

コード:

public class DirSize
{
    public static void main(String[] args)
    {
        DirSize ds = new DirSize();
        System.out.println(ds.getDirSizeInMegabytes(new File("c:/temp")));
    }

    long getDirSize(File dir)
    {
        long size = 0;

        if (dir.isFile())
        {
            size = dir.length();
        }
        else
        {
            File[] subFiles = dir.listFiles();

            for (File file : subFiles)
            {
                if (file.isFile())
                {
                    size += file.length();
                }
                else
                {
                    size += this.getDirSize(file);
                    System.out.println("Directory " + file.getName()
                                       + " size = " + size / 1021 / 1024);
                }
            }
        }
        return size;
    }

    long getDirSizeInMegabytes(File dir)
    {
        return this.getDirSize(dir) / 1024 / 1024;
    }
}

たとえば、最初から2番目のレベルにあるディレクトリのみのサイズを印刷したいと思います。

c:\temp1\temp2

しかし、temp3もある場合:

c:\temp1\temp2\temp3 its size shouldn't be printed.

好き:

 c:\temp1\temp2 size = 10M
 c:\temp1\temp21 size = 15M
 ....

どのようにそれを行うことができますか?ありがとう。

4

2 に答える 2

2

印刷される内容を制限できるようにするには、再帰メソッドに再帰の深さを追加する必要があります。

long getDirSize(File dir, int depth, int printDepth) 

次に、次のような再帰呼び出しが必要です。

size += this.getDirSize(file, depth+1, printDepth);

また、maxdepthでサイズのみを印刷する場合は、次のようなテストを追加する必要があります。

if (depth == printDepth) { // or depth <= printDepth maybe
    // ...do printing only for these
}

すべてをクラスでラップすることは理にかなっているかもしれません。そのため、printDepthをメンバー変数にし、再帰メソッドを次のようにプライベートにすることができます。

class DirSizePrinter {
    int printDepth;
    File root;
    public DirSizePrinter(int printDepth, File root) {
        this.printDepth = printDepth;
        this.root = root;
    }

    public long printSize() {
        return printSizeRecursive(0);
    }

    private long printSizeRecursive(int depth) {
        // ... code from question with depth added, and using printDepth and root
    }
}

使用法:

    new DirSizePrinter(3, "C:/temp").printSize();

または、あなたが持っているすべての要件に応じて、これのいくつかのバリエーション。

于 2012-12-20T09:27:41.680 に答える
1
void getDirSize(File dir,depth) {
    long size = 0;

    if (dir.isFile()) {
        size = dir.length();
    } else {
        depth++;
        File[] subFiles = dir.listFiles();

        for (File file : subFiles) {
            if (file.isFile()) {
                size += file.length();
            } else {
                size += this.getDirSize(file,depth);
                if(depth==1) {
                System.out.println("Directory " + file.getName()
                        + " size = " + size / 1021 / 1024);
}
            }

        }
    }

}

その後、電話

getDirSize(new File("c:/temp"),0)
于 2012-12-20T09:31:01.030 に答える