List all directories in directory java

Creating and Reading Directories

Some of the methods previously discussed, such as delete , work on files, links and directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?

This section covers the following functionality specific to directories:

Listing a File System’s Root Directories

You can list all the root directories for a file system by using the FileSystem.getRootDirectories method. This method returns an Iterable , which enables you to use the enhanced for statement to iterate over all the root directories.

The following code snippet prints the root directories for the default file system:

Iterable dirs = FileSystems.getDefault().getRootDirectories(); for (Path name: dirs)

Creating a Directory

You can create a new directory by using the createDirectory(Path, FileAttribute) method. If you don’t specify any FileAttributes , the new directory will have default attributes. For example:

Path dir = . ; Files.createDirectory(path);

The following code snippet creates a new directory on a POSIX file system that has specific permissions:

Set perms = PosixFilePermissions.fromString("rwxr-x---"); FileAttribute attr = PosixFilePermissions.asFileAttribute(perms); Files.createDirectory(file, attr);

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute) . As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

Creating a Temporary Directory

You can create a temporary directory using one of createTempDirectory methods:

The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file directory.

Listing a Directory’s Contents

You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable , so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.

Remember: The returned DirectoryStream is a stream. If you are not using a try- with-resources statement, don’t forget to close the stream in the finally block. The try- with-resources statement takes care of this for you.

The following code snippet shows how to print the contents of a directory:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir)) < for (Path file: stream) < System.out.println(file.getFileName()); >> catch (IOException | DirectoryIteratorException x) < // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); >

The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a , /tmp/b , and so on.

This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.

Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.

Filtering a Directory Listing By Using Globbing

If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using the newDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, see What Is a Glob?

For example, the following code snippet lists files relating to Java: .class, .java, and .jar files.:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.")) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x) < // IOException can never be thrown by the iteration. // In this snippet, it can // only be thrown by newDirectoryStream. System.err.println(x); >

Writing Your Own Directory Filter

Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter interface. This interface consists of one method, accept , which determines whether a file fulfills the search requirement.

For example, the following code snippet implements a filter that retrieves only directories:

DirectoryStream.Filter filter = newDirectoryStream.Filter() < public boolean accept(Path file) throws IOException < try < return (Files.isDirectory(path)); >catch (IOException x) < // Failed to determine if it's a directory. System.err.println(x); return false; >> >;

Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter) method. The following code snippet uses the isDirectory filter to print only the directory’s subdirectories to standard output:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, filter)) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x)

This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism for Walking the File Tree.

Источник

Java File IO List files and directories Example

In Java, to query a list of files and directories in a specific directory, we use the File class under java.io package and follow these steps:

File dir = new File(“C:/Path/To/My/Directory”);

    • Use one of the following methods of the File class:
        1. String[] list()
        2. String[] list(FilenameFilter filter)
        3. File[] listFiles()
        4. File[] listFiles(FileFilter filter)
        5. File[] list(FilenameFilter filter)
          • If you just want to get names of the files and directories, use the methods that return an array of Strings, the list() methods (method 1 and 2).
          • If you want to get a list of File objects in order to do something with the files, then go with the methods that return an array of File object, the listFiles() methods (method 3, 4 and 5).
          • If you want to list all files and directories in the specified directory, use the no-argument methods (method 1 and 3)
          • If you don’t want to list all files and directories, but some kind of files based on some conditions, then go with the methods that accept a FilenameFilter or FileFilter as an argument (method 2, 4, and 5). Then you have to create a class that implements either the interface FilenameFilter or FileFilter, and override their methods accept(File dir, String name) or accept(File pathname) , respectively.
            • The list() methods return an array of Strings.
            • The listFiles() methods return an array of File objects.
            • The non-argument methods list everything under the directory.
            • The argument-based methods list only files and directories which satisfy the filter you provided.

            Java Directory Listing Code Example 1 :

            String dirPath = "g:/Music/English"; File dir = new File(dirPath); String[] files = dir.list(); if (files.length == 0) < System.out.println("The directory is empty"); >else < for (String aFile : files) < System.out.println(aFile); >>

            This example uses String[] list() method to get names of files and directories just as Strings, and you can’t do anything further with the files/directories.

            Java Directory Listing Code Example 2:

            String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(); if (files.length == 0) < System.out.println("The directory is empty"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>

            This example uses File[] listFiles() method to retrieve an array of File objects, so you can do something more with an individual file or directory, such as getting absolute path or file size.

            Java Directory Listing Code Example 3:

            Suppose we want to list only MP3 files, create a local class that implements the interface FilenameFilter , and overrides the accept(File file, String name) method as follows:

            FilenameFilter mp3Filter = new FilenameFilter() < public boolean accept(File file, String name) < if (name.endsWith(".mp3")) < // filters files whose extension is .mp3 return true; >else < return false; >> >;

            If the accept() method returns true, the file will be listed. Then call the method listFiles(FilenameFilter filter) as follows:

            String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(mp3Filter); if (files.length == 0) < System.out.println("There is no MP3 files"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>

            Note: as the name suggests, the FilenameFilter interface is for filtering file names only. If you want to filter other file’s properties such as size or modification time, use the method listFiles(FileFilter filter)

            Java Directory Listing Code Example 4 :

            Suppose you want to list only the files whose size is greater than 3MB, create a local class that implements the interface FileFilter , and overrides the accept(File file) method as follows:

            FileFilter sizeFilter = new FileFilter() < public boolean accept(File file) < if (file.isFile() && file.length() >3*1024*1024) < // filters files whose size greater than 3MB return true; >else < return false; >> >;

            Then call the method listFiles(FileFilter filter) as follows:

            String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(sizeFilter); if (files.length == 0) < System.out.println("There is no files bigger than 3MB"); >else < for (File aFile : files) < System.out.println(aFile.getName() + " - " + aFile.length()); >>

            Other Java File IO Tutorials:

            About the Author:

            Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

            Источник

            Java File IO — List files and directories recursively

            The article How to list files and directories in a directory explains very well about how to list all files and directories under a specific directory, however its examples are only for listing the first level files and directories (those which are directly under the parent directory). But a directory may contain many sub files and sub directories which are nested in many levels, as in the following screenshot, for example:

            a directory

            To list all sub files and sub directories nested in all levels, one solution is to use recursion algorithm:

            1. List files in the first level.
            2. For each file in the first level list files:
              1. If the file is a directory:
                • Print out directory name.
                • Repeat the step 1 and 2 with the current directory.
              2. If the file is a file:
                • Print out file name.
              3. Continue with next file.
              public void listDirectory(String dirPath, int level) < File dir = new File(dirPath); File[] firstLevelFiles = dir.listFiles(); if (firstLevelFiles != null && firstLevelFiles.length >0) < for (File aFile : firstLevelFiles) < for (int i = 0; i < level; i++) < System.out.print("\t"); >if (aFile.isDirectory()) < System.out.println("[" + aFile.getName() + "]"); listDirectory(aFile.getAbsolutePath(), level + 1); >else < System.out.println(aFile.getName()); >> > >

              The listDirectory() method has two parameters:

Оцените статью