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.
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 #
Don't forget to call the close method of DirectoryStream after you're done with it!!
Posted by Optimus on November 08, 2014 at 12:50 PM CET #
Thank you
Posted by ritcher1 on July 25, 2016 at 05:01 PM CEST #
You idiot !
Your code doesn't even compile.
Posted by Bob on December 09, 2016 at 03:24 AM CET #
File version also has filtering support
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#list(java.io.FilenameFilter)
Posted by foo on May 07, 2017 at 03:13 PM CEST #
@ritcher1 - Didn't work for me on my ZX spectrum either.
Posted by P Ba on June 27, 2019 at 06:55 PM CEST #