Programing

Java, 파일이 아닌 디렉토리의 하위 디렉토리 만 나열

lottogame 2020. 9. 8. 21:54
반응형

Java, 파일이 아닌 디렉토리의 하위 디렉토리 만 나열


Java에서 디렉토리의 하위 디렉토리 만 나열하려면 어떻게합니까?

java.io.File 기능을 사용하고 싶습니다.이 작업을 수행하는 데 Java에서 가장 좋은 방법은 무엇입니까?


File 클래스를 사용 하여 디렉토리를 나열 할 수 있습니다 .

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

최신 정보

이 게시물에 대한 작성자의 의견은 더 빠른 방법을 원했고 여기에 훌륭한 토론이 있습니다. Java에서 디렉토리 목록을 빠르게 검색하는 방법?

원래:

  1. 파일 구조를 제어한다면 그 상황에 빠지지 않으려 고 노력할 것입니다.
  2. Java NIO.2에서는 디렉토리 함수를 사용하여 더 큰 확장을 허용하는 반복자를 반환 할 수 있습니다. 디렉토리 스트림 클래스는 디렉토리의 항목을 반복하는 데 사용할 수있는 객체입니다.

매우 간단한 Java 8 솔루션 :

File[] directories = new File("/your/path/").listFiles(File::isDirectory);

FileFilter를 사용하는 것과 동일합니다 (이전 Java에서도 작동).

File[] directories = new File("/your/path/").listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.isDirectory();
    }
});

@Mohamed Mansour 당신은 거의 거기에있었습니다 ... 당신이 사용하고 있던 "dir"인수는 실제로 현재의 경로이므로 항상 true를 반환합니다. 하위 디렉토리가 하위 디렉토리인지 확인하려면 해당 하위 디렉토리를 테스트해야합니다.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

Java 7 및 NIO.2를 사용하는 솔루션에 관심이있는 경우 다음과 같이 진행할 수 있습니다.

private static class DirectoriesFilter implements Filter<Path> {
    @Override
    public boolean accept(Path entry) throws IOException {
        return Files.isDirectory(entry);
    }
}

try (DirectoryStream<Path> ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(root), new DirectoriesFilter())) {
        for (Path p : ds) {
            System.out.println(p.getFileName());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Java 7 및 NIO에도 관심이있는 사람들을 위해 위의 @voo 답변에 대한 대안 솔루션이 있습니다. 호출 하는 try-with-resourcesFiles.find() 와 디렉터리를 필터링하는 데 사용되는 람다 함수를 사용할 수 있습니다.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;


final Path directory = Paths.get("/path/to/folder");

try (Stream<Path> paths = Files.find(directory, Integer.MAX_VALUE, (path, attributes) -> attributes.isDirectory())) {
    paths.forEach(System.out::println);
} catch (IOException e) {
    ...
}

람다 함수를 변경하여 이름으로 디렉터리를 필터링 할 수도 있습니다.

(path, attributes) -> attributes.isDirectory() && path.toString().contains("test")

또는 날짜 별 :

final long now = System.currentTimeMillis();
final long yesterday = new Date(now - 24 * 60 * 60 * 1000L).getTime();

// modified in the last 24 hours
(path, attributes) -> attributes.isDirectory() && attributes.lastModifiedTime().toMillis() > yesterday

ArrayList<File> directories = new ArrayList<File>(
    Arrays.asList(
        new File("your/path/").listFiles(File::isDirectory)
    )
);

시작 디렉토리가 String

  1. Create a method that takes a String path as the parameter. In the method:
  2. Create a new File object based on the starting directory
  3. Get an array of files in the current directory using the listFiles method
  4. Loop over the array of files
    1. If it's a file, continue looping
    2. If it's a directory, print out the name and recurse on this new directory path

Here is solution for my code. I just did a litlle change from first answer. This will list all folders only in desired directory line by line:

try {
            File file = new File("D:\\admir\\MyBookLibrary");
            String[] directories = file.list(new FilenameFilter() {
              @Override
              public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
              }
            });
            for(int i = 0;i < directories.length;i++) {
                if(directories[i] != null) {
                    System.out.println(Arrays.asList(directories[i]));

                }
            }
        }catch(Exception e) {
            System.err.println("Error!");
        }

The solution that worked for me, is missing from the list of answers. Hence I am posting this solution here:

File[]dirs = new File("/mypath/mydir/").listFiles((FileFilter)FileFilterUtils.directoryFileFilter());

Here I have used org.apache.commons.io.filefilter.FileFilterUtils from Apache commons-io-2.2.jar. Its documentation is available here: https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/filefilter/FileFilterUtils.html


I'd like to use the java.io.File functionality,

In 2012 (date of the question) yes, not today. java.nio API has to be favored for such requirements.

Terrible with so many answers, but not the simple way that I would use that is Files.walk().filter().collect().

Globally two approaches are possible :

1)Files.walk(Path start, ) has no maxDepth limitations while

2)Files.walk(Path start, int maxDepth, FileVisitOption... options) allows to set it.

Without specifying any depth limitation, it would give :

Path directory = Paths.get("/foo/bar");

try {
    List<Path> directories =
            Files.walk(directory)
                 .filter(Files::isDirectory)
                 .collect(Collectors.toList());
} catch (IOException e) {
    // process exception
}

And if for legacy reasons, you need to get a List of File you can just add a map(Path::toFile) operation before the collect :

Path directory = Paths.get("/foo/bar");

try {
    List<File> directories =
            Files.walk(directory)
                 .filter(Files::isDirectory)
                 .map(Path::toFile)
                 .collect(Collectors.toList());
} catch (IOException e) {
    // process exception
}

참고URL : https://stackoverflow.com/questions/5125242/java-list-only-subdirectories-from-a-directory-not-files

반응형