Listing Directory Content

Java NIO - List Directory Contents

  • Java
  • 2 mins read

In Java, use NIO static newDirectoryStream() method to list directory contents.

Syntax

static DirectoryStream<Path> newDirectoryStream(Path directory_path)

Here, directory_path encapsulates the path to the directory. The method newDirectoryStream() returns a DirectoryStream<Path> object that can be used to list the directory contents.

Java NIO newDirectoryStream() Example

The following program lists the contents of the directory "/User/vinish/Code/temp":

// DirectoryList.java

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

public class DirectoryList {

    public static void main(String args[]) {
        String dirname = "//User//vinish//Code//temp";

        try (DirectoryStream<Path> dirstrm
                = Files.newDirectoryStream(Paths.get(dirname))) {
            System.out.println("Listing files for directory " + dirname);

            for (Path entry : dirstrm) {
                BasicFileAttributes attribs
                        = Files.readAttributes(entry, BasicFileAttributes.class);

                if (attribs.isDirectory()) {
                    System.out.print("<DIR> ");
                } else {
                    System.out.print("      ");
                }
// Note: Here to get file name, using the value 4, because the directory is 4 level deep
                System.out.println(entry.getName(4));

            }

        } catch (InvalidPathException e) {
            System.out.println("Path Error " + e);
        } catch (NotDirectoryException e) {
            System.out.println(dirname + " is not a directory.");

        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        }
    }

}

Output

Listing files for directory //User//vinish//Code//temp
<DIR> Cache
      howto.json
      temp2.txt

See also: