ファイルインスタンスはFileNameFilterインターフェイスのラムダ式の中に構築する必要があります

変異アルゴリズム:

私は私のテストのために次のディレクトリ構造を持っていると仮定します。

test
|
|
---test1
|
|
---test2
|
|
---random.txt

random.txtが通常のファイルである一方、この構造では、TEST1とTEST2はディレクトリです。

私は私にファイルのパスを指定したすべてのサブディレクトリのリストを与える機能を書きたいです。

1、作品(無ラムダ式を)しようとします

private static ArrayList<String> subDirectories(File pathname) {
    ArrayList<String> subdirectories = new ArrayList<>();

    for(File file : pathname.listFiles()) {
        if(file.isDirectory())
            subdirectories.add(file.getName());
    }

    return subdirectories;
}

これは正しくサブディレクトリとしてTEST1とTEST2を返します。

試み2:ラムダ式を使用して

private static String[] subDirectories(File pathname) {
    return pathname.list((dir, name) -> dir.isDirectory());
}

この結果は、今では明らかにされていない、ディレクトリとしてrandom.txtが含まれています。なぜラムダは異なる結果を与えると機能がありますか?

EDIT:

ラムダ式でファイルのインスタンスを作成する場合にのみ動作します。

return pathname.list((dir, name) -> new File(dir, name).isDirectory());

DIRは、なぜ我々は、既存のファイルのインスタンスからFileインスタンスを作成している、しかし、すでにFileオブジェクトのですか?

EDIT 2:

ドキュメントを見た後、dirパラメータは、常にファイルが見つかったディレクトリを指します。理由はここにありrandom.txt、ディレクトリの名前として返されます。新しいFileのインスタンスを作成が必要な理由しかし、私はまだ知りません。

また:

既存の試みと同様に:

private static List<String> subDirectories(File pathname) {
    return Arrays.stream(pathname.listFiles())
                   .filter(File::isDirectory)
                   .map(File::getName)
                   .collect(Collectors.toList());
}

ラムダ・ソリューション・リストが理由random.txtで使用されるFilenameFilterようにパラメータを使用します:

/**
 * Tests if a specified file should be included in a file list.
 *
 * @param   dir    the directory in which the file was found.
 * @param   name   the name of the file.
 * @return  true if and only if the name should be
 *          included in the file list; false otherwise.
 */
boolean accept(File dir, String name);

あなたは、関連することができてtest、ディレクトリであるとのは、なぜそのrandom.txt出力に濾過されます


編集:使用

return pathname.list((dir, name) -> new File(dir, name).isDirectory());

あなたが名前のファイルではなくディレクトリを作成しました、以来作品random.txtそのないディレクトリがに記載されている理由のjavadoc

親である場合は、空の抽象パス名、新しいFileのインスタンスは、childを抽象パス名に変換し、システムに依存するデフォルトのディレクトリに対する結果を解決することで生成されます。

あなたのケースでどの親ディレクトリが存在するので、当てはまりません。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=364267&siteId=1