Adam Bien's Weblog
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.
Posted at 10:38PM Nov 23, 2012 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Comments[1] | Views/Hits: 3688
NEW Workshop: "JPA, NoSQL, Caching, Grids and Distributed Caches with Java EE 7", May 7th, 2013, Airport Munich
A book about rethinking Java EE Patterns
Tweet Follow @AdamBien

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 01:47 PM CET #