Java example list files

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.

            Источник

            Listing All Files in a Directory in Java

            Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

            • For using external iteration (for loop) use DirectoryStream .
            • For using Stream API operations, use Files.list() instead.

            1. Listing Files Only in a Given Directory

            1.1. Sream of Files with Files.list()

            If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, then we can use this approach.

            • Read all files and directories entries using Files.list().
            • Check if a given entry is a file using PredicateFile::isFile.
            • Collect all filtered entries into a List.
            //The source directory String directory = "C:/temp"; // Reading only files in the directory try < Listfiles = Files.list(Paths.get(directory)) .map(Path::toFile) .filter(File::isFile) .collect(Collectors.toList()); files.forEach(System.out::println); > catch (IOException e)

            1.2. DirectoryStream to Loop through Files

            DirectoryStream is part of Java 7 and is used to iterate over the entries in a directory in for-each loop style.

            Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed.

            List fileList = new ArrayList<>(); try (DirectoryStream stream = Files .newDirectoryStream(Paths.get(directory))) < for (Path path : stream) < if (!Files.isDirectory(path)) < fileList.add(path.toFile()); >> > fileList.forEach(System.out::println);

            2. Listing All Files in Given Directory and Sub-directories

            2.1. Files.walk() for Stream of Paths

            The walk() method returns a Stream by walking the file tree beginning with a given starting file/directory in a depth-first manner.

            Note that this method visits all levels of the file tree.

            String directory = "C:/temp"; List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .collect(Collectors.toList()); >pathList.forEach(System.out::println);

            If you wish to include the list of Path instances for directories as well, then remove the filter condition Files::isRegularFile.

            We can also write the file tree walking logic using the recursion. It gives a little more flexibility if we want to perform some intermediate steps/checks before adding the entry to list of the files.

            String directory = "C:/temp"; //Recursively list all files List fileList = listFiles(directory); fileList.forEach(System.out::println); private static List listFiles(final String directory) < if (directory == null) < return Collections.EMPTY_LIST; >List fileList = new ArrayList<>(); File[] files = new File(directory).listFiles(); for (File element : files) < if (element.isDirectory()) < fileList.addAll(listFiles(element.getPath())); >else < fileList.add(element); >> return fileList; >

            Please note that if we’re working with a large directory, then using DirectoryStream performs better.

            3. Listing All Files of a Certain Extention

            To get the list of all files of certain extensions only, use two predicates Files::isRegularFile and filename.endsWith(«.extension») together.

            In given example, we are listing all .java files in a given directory and all of its sub-directories.

            String directory = "C:/temp"; //Recursively list all files List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < // Do something with the stream. pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .filter(path ->path.getFileName().toString().endsWith(".java")) .collect(Collectors.toList()); > pathList.forEach(System.out::println); >

            4. Listing All Hidden Files

            To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples.

            List files = Files.list(Paths.get(dirLocation)) .filter(path -> path.toFile().isHidden()) .map(Path::toFile) .collect(Collectors.toList());

            In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods. Feel free to modify the code and play with it.

            Источник

            How to list all files in a directory in Java

            In Java, there are many ways to list all files and folders in a directory. You can use either the Files.walk() , Files.list() , or File.listFiles() method to iterate over all the files available in a certain directory.

            The Files.walk() is another static method from the NIO API to list all files and sub-directories in a directory. This method throws a NoSuchFileException exception if the folder doesn’t exist. Here is an example that lists all files and sub-directories in a directory called ~/java-runner :

            try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // print all files and folders paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

            Since it returns a Stream object, you can filter out nested directories and only list regular files like below:

            try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // filer out sub-directories ListString> files = paths.filter(x -> Files.isRegularFile(x)) .map(Path::toString) .collect(Collectors.toList()); // print all files files.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 
            try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // filer out regular files ListString> folders = paths.filter(x -> Files.isDirectory(x)) .map(Path::toString) .collect(Collectors.toList()); // print all folders folders.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 
            try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // keep only `.java` files ListString> javaFiles = paths.map(Path::toString) .filter(x -> x.endsWith(".java")) .collect(Collectors.toList()); // print all files javaFiles.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

            By default, the Stream object returned by Files.walk() recursively walks through the file tree up to an n-level (all nested files and folders). However, you can pass another parameter to Files.walk() to limit the maximum number of directory levels to visit. Here is an example that restricts the directory level to a top-level folder only (level 1):

            try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"), 1))  // print all files and folders in the current folder paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

            In the above code, the second parameter of Fils.walk() is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of Integer.MAX_VALUE indicatea that all levels should be traversed.

            The Files.list() static method from NIO API provides the simplest way to list the names of all files and folders in a given directory:

            try (StreamPath> paths = Files.list(Paths.get("~/java-runner")))  // print all files and folders paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

            The Files.list() method returns a lazily populated Stream of entries in the directory. So you can apply all the above filters for Files.walk() on the stream.

            In old Java versions (JDK 6 and below), the File.listFiles() method is available to list all files and nested folders in a directory. Here is an example that uses File.listFiles() to print all files and folders in the given directory:

            File folder = new File("~/java-runner"); // list all files for (File file : folder.listFiles())  System.out.println(file); > 
            File folder = new File("~/java-runner"); // list all regular files for (File file : folder.listFiles())  if (file.isFile())  System.out.println(file); > > 
            File folder = new File("~/java-runner"); // list all sub-directories for (File file : folder.listFiles())  if (file.isDirectory())  System.out.println(file); > > 
            public void listFilesRecursive(File folder)  for (final File file : folder.listFiles())  if (file.isDirectory())  // uncomment this to list folders too // System.out.println(file); listFilesRecursive(file); > else  System.out.println(file); > > > // list files recursively File folder = new File("~/java-runner"); listFilesRecursive(folder); 

            ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

            You might also like.

            Источник

            Читайте также:  Style display inline javascript
Оцените статью