Adam Bien's Weblog

Friday Nov 23, 2012

Listing Directory Contents with JDK 1.7 and NIO.2


import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;


    public static List<String> fileList(String directory) {
        List<String> fileNames = new ArrayList<>();
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directory))) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }

The JDK 1.0 version is a bit shorter:


String[] directories = new File("dir").list();

However: Because the DirectoryStream is a "lazy" Iterable the NIO.2 version is better suitable for directories with lots of contents. Also the JDK 1.7 version supports out-of-the-box filtering.


NEW workshop: Microservices with Java EE 7 and Java 8, January 26th, 2015, Airport Munich

A book about rethinking Java EE Patterns

Comments:

I make heavy usage of the following methods due to the greater flexibility of using Path.
Path and Files have many methods to manage system files.

public List<Path> getDirectories(final Path dir) throws IOException {
final List<Path> dirlist = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (final Iterator<Path> it = stream.iterator(); it.hasNext();) {
dirlist.add(dir.resolve(it.next()));
}
}
return dirlist;
}

public List<Path> getEntries(final Path dir) throws IOException {
final List<Path> entries = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (final Iterator<Path> it = stream.iterator(); it.hasNext();) {
entries.add(it.next());
}
}
return entries;
}

public List<Path> getEntries(final Path dir, final DirectoryStream.Filter<? super Path> filter) throws IOException {
final List<Path> entries = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
for (final Iterator<Path> it = stream.iterator(); it.hasNext();) {
entries.add(it.next());
}
}
return entries;
}

public List<Path> getEntries(final Path dir, final String glob) throws IOException {
final List<Path> entries = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, glob)) {
for (final Iterator<Path> it = stream.iterator(); it.hasNext();) {
entries.add(it.next());
}
}
return entries;
}

Posted by Carlos Hoces on November 24, 2012 at 02:47 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License