44

指定したディレクトリ内のすべてのファイルと、そのディレクトリ内のサブディレクトリを一覧表示したいと考えています。ディレクトリをリストする必要はありません。

私の現在のコードは以下です。指定したディレクトリ内のファイルとディレクトリのみを一覧表示するため、正しく機能しません。

どうすればこれを修正できますか?

final List<Path> files = new ArrayList<>();

Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
try
{
  DirectoryStream<Path> stream;
  stream = Files.newDirectoryStream(path);
  for (Path entry : stream)
  {
    files.add(entry);
  }
  stream.close();
}
catch (IOException e)
{
  e.printStackTrace();
}

for (Path entry: files)
{
  System.out.println(entry.toString());
}
4

9 に答える 9

76

Java 8 は、そのための優れた方法を提供します。

Files.walk(path)

このメソッドは を返しますStream<Path>

于 2016-04-23T19:06:18.347 に答える
32

次の要素がディレクトリの場合に自分自身を呼び出すメソッドを作成します

void listFiles(Path path) throws IOException {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
                listFiles(entry);
            }
            files.add(entry);
        }
    }
}
于 2014-01-08T04:56:09.673 に答える
6

関数が自分自身を再帰的に呼び出したり、メンバー変数であるファイル リストを使用したりすることを避けたい場合は、スタックを使用できます。

private List<Path> listFiles(Path path) throws IOException {
    Deque<Path> stack = new ArrayDeque<Path>();
    final List<Path> files = new LinkedList<>();

    stack.push(path);

    while (!stack.isEmpty()) {
        DirectoryStream<Path> stream = Files.newDirectoryStream(stack.pop());
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
                stack.push(entry);
            }
            else {
                files.add(entry);
            }
        }
        stream.close();
    }

    return files;
}
于 2014-05-07T13:34:21.657 に答える
2

実装を完了します。簡単なチェックだけで、サブフォルダーからすべてのファイルが読み取られます。

Path configFilePath = FileSystems.getDefault().getPath("C:\\Users\\sharmaat\\Desktop\\issue\\stores");
List<Path> fileWithName = Files.walk(configFilePath)
                .filter(s -> s.toString().endsWith(".java"))
                .map(Path::getFileName)
                .sorted()
                .collect(Collectors.toList());

for (Path name : fileWithName) {
    // printing the name of file in every sub folder
    System.out.println(name);
}
于 2019-11-27T13:22:53.017 に答える
-1

試してみてください: ディレクトリとサブディレクトリ パスのリストが表示されます。無制限のサブディレクトリがある可能性がありrecursiveます。プロセスを使用してみてください。

public class DriectoryFileFilter {
    private List<String> filePathList = new ArrayList<String>();

    public List<String> read(File file) {
        if (file.isFile()) {
            filePathList.add(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            File[] listOfFiles = file.listFiles();
            if (listOfFiles != null) {
                for (int i = 0; i < listOfFiles.length; i++){
                    read(listOfFiles[i]);
                }
            } else {
                System.out.println("[ACCESS DENIED]");
            }
        }
        return filePathList;
    }
}
于 2014-01-08T05:44:10.747 に答える