Java list all folders in a folder

Get list of files and sub-directories in a directory in Java

In this Java tutorial, you will learn how to get the list of files and sub-directories in a given folder, with examples.

Java – Filter files or sub-directories in a directory

You can get the list of files and sub-directories in a given folder using Java. We can also filter the list based on extension or a specific condition.

In this Java Tutorial, we shall learn how to perform the following tasks.

  • Extract list of files and directories in a folder using java
  • Extract list of files belonging to specific file type
  • Extract list of files belonging to specific file type, present in the folder and its sub folders/directories

Extract list of files and sub-directories in a directory

Follow these steps to extract the names of files and sub directories in a given directory.

Step 1 : Specify the folder. In this example, “sample” is the folder name placed at the root to the project.

File folder = new File("sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Читайте также:  Parse http header python

Step 4 : Check if an item in the folder is a directory.

Complete program that lists the files and directories in a folder is given below.

ListOfFilesExample.java

import java.io.File; import java.util.ArrayList; import java.util.List; /** * Program that gives list of files or directories in a folder using Java */ public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < files.add(listOfFiles[i].getName()); >else if (listOfFiles[i].isDirectory()) < directories.add(listOfFiles[i].getName()); >> System.out.println("List of files :\n---------------"); for(String fName: files) System.out.println(fName); System.out.println("\nList of directories :\n---------------------"); for(String dName: directories) System.out.println(dName); > >

The sample folder and its contents are as shown in the below picture :

list of files or directories in a foder using Java - Java Tutorial - tutorialkart.com

When the program is run, output to the console would be as shown below.

List of files : --------------- html_file_1.html text_file_1.txt text_file_3.txt text_file_2.txt List of directories : --------------------- directory_1 directory_2

Get list of files of specific extension from the directory

Step 1 : Specify the folder.

File folder = new File("sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Step 4 : Check if the file belong to specified file-type.

Check the extension of the filename with String.endsWith(suffix)

listOfFiles[i].getName().endsWith(fileExtension)

Complete program to get the list of files, that belong to a specified extension type is shown below.

ListOfFilesExample.java

import java.io.File; import java.util.ArrayList; import java.util.List; public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); String fileExtension = ".txt"; File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< files.add(listOfFiles[i].getName()); >> > System.out.println("List of .txt files :\n--------------------"); for(String fName: files) System.out.println(fName); > >

When the program is run, Output to the console would be as shown below.

List of .txt files : -------------------- text_file_1.txt text_file_3.txt text_file_2.txt

Get list of files with specific extension from the directory and its sub-directories

Step 1 : Specify the folder.

File folder = new File("D:"+File.separator+"Arjun"+File.separator+"sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Step 4 : Check if the file belong to specified file-type.

Check the extension of the filename with String.endsWith(suffix)

listOfFiles[i].getName().endsWith(fileExtension)

Step 5 : Check if an item in the folder is a directory.

Step 6 : Get the list of files (beloging to specific file-type) recursively from all the sub-directories.

The complete program is given below.

FileListExtractor.java

import java.io.File; import java.util.ArrayList; import java.util.List; public class FileListExtractor < List allTextFiles = new ArrayList(); String fileExtension = ".txt"; public static void main(String[] args) < FileListExtractor folderCrawler = new FileListExtractor(); folderCrawler.crawlFold("sample"); System.out.println("All text files in the folder \"sample\" and its sub directories are :\n---------------------------------------------------------------"); for(String textFileName:folderCrawler.allTextFiles)< System.out.println(textFileName); >> public void crawlFold(String path) < File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< allTextFiles.add(listOfFiles[i].getName()); >> else if (listOfFiles[i].isDirectory()) < // if a directory is found, crawl the directory to get text files crawlFold(path+File.separator+listOfFiles[i].getName()); >> > >

When the program is run, output to the console is

All text files in the folder "sample" and its sub directories are : --------------------------------------------------------------- text_file_2_1.txt text_file_1_1.txt text_file_2_1.txt text_file_1_1.txt text_file_2_2.txt text_file_1_2.txt text_file_1.txt text_file_3.txt text_file_2.txt

Conclusion

In this Java Tutorial, we learned how to list all the files and sub-directories in a given folder.

Источник

How to get list of all files/folders from a folder in Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

To get the list of all the existing files in a directory this class provides the files class provides list() (returns names) and ListFiles (returns File objects) with different variants.

The List() method

This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object.

Using this method, you can just print the names of the files and directories.

Example

The following Java program lists the names of all the files and directories in the path D:\ExampleDirectory.

import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories String contents[] = directoryPath.list(); System.out.println("List of files and directories in the specified directory:"); for(int i=0; i> >

Output

List of files and directories in the specified directory: SampleDirectory1 SampleDirectory2 SampleFile1.txt SampleFile2.txt SapmleFile3.txt

The ListFiles() method

This method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

Since this method returns the objects of each file/directory in a folder. Using it you can access the properties of the files/directories such as size, path etc.

Example

The following Java program prints the name, path and, size of all the files in the path D:\ExampleDirectory.

import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories File filesList[] = directoryPath.listFiles(); System.out.println("List of files and directories in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of files and directories in the specified directory: File name: SampleDirectory1 File path: D:\ExampleDirectory\SampleDirectory1 Size :262538260480 File name: SampleDirectory2 File path: D:\ExampleDirectory\SampleDirectory2 Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

The List(FilenameFilter filter) method

As suggested in its signature, this method accepts a FilenameFilter object and returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter.

Using this method, you can get the filtered names of the files and directories in a particular folder.

Example

The following Java program prints the names of the text files in the path D:\ExampleDirectory.

import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files String filesList[] = directoryPath.list(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(String fileName : filesList) < System.out.println(fileName); >> >

Output

List of the text files in the specified directory −

SampleFile1.txt SampleFile2.txt SapmleFile3.txt

The ListFiles(FilenameFilter filter) method

This method accepts a FilenameFilter object and returns a File array containing the objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on their name

Using this method, you can get the filtered file objects of the files and directories in a particular folder, according to their names.

Example

The following Java program prints the name, path and, size of all the text files in the path D:\ExampleDirectory.

import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of the text files in the specified directory: File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

The ListFiles(FileFilter filter) method

This method accepts a FileFilter object and returns a File array containing the (File) objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on the property of the file.

Using this method, you can get the filtered file objects of the files and directories in a particular folder based on the size, path, type (file or, directory) etc…

Example

The following Java program prints the name, path and, size of all the files (not folders) in the path D:\ExampleDirectory.

import java.io.File; import java.io.FileFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FileFilter textFilefilter = new FileFilter()< public boolean accept(File file) < boolean isFile = file.isFile(); if (isFile) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >

Output

List of the text files in the specified directory: File name: cassandra_logo.jpg File path: D:\ExampleDirectory\cassandra_logo.jpg Size :262538260480 File name: cat.jpg File path: D:\ExampleDirectory\cat.jpg Size :262538260480 File name: coffeescript_logo.jpg File path: D:\ExampleDirectory\coffeescript_logo.jpg Size :262538260480 File name: javafx_logo.jpg File path: D:\ExampleDirectory\javafx_logo.jpg Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480

Источник

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