0

Я знаю как обойти все файлы использую рекурсию

        public static void getListFiles(String str) {
            File f = new File(str);
            for (File s : f.listFiles()) {
                if (s.isFile()) {
                    listWithFileNames.add(s);
                } else if (s.isDirectory()) {
                    getListFiles(s.getAbsolutePath());
                }
            }

        }

А как получить список всех файлов используя методы из java.nio?

1 ответ 1

3

Начиная с Java 1.7

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class FileTree {
    public static void main(String[] args) {

        Path pathSource = Paths.get("Введите сюда путь к какому-либо каталогу, содержащему другие каталоги и файлы");
        try {
            Files.walkFileTree(pathSource, new MyFileVisitor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class MyFileVisitor extends SimpleFileVisitor {
    public FileVisitResult visitFile(Path path,
                                     BasicFileAttributes fileAttributes) {
        System.out.println("file name:" + path.getFileName());
        return FileVisitResult.CONTINUE;
    }

    public FileVisitResult preVisitDirectory(Path path,
                                             BasicFileAttributes fileAttributes) {
        System.out.println("Directory name:" + path);
        return FileVisitResult.CONTINUE;
    }
}

The Java™ Tutorials - Walking the File Tree

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.