Java read files in folders

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

Читайте также:  Python load module class

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

Источник

How to read data from all files in a directory using Java?

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

Читайте также:  Java what is an interface definition

To get the list of all the existing files in a directory this class provides five different methods to get the details of all files in a particular folder −

  • String[] list()
  • File[] listFiles()
  • String[] list(FilenameFilter filter)
  • File[] listFiles(FilenameFilter filter)
  • File[] listFiles(FileFilter filter)

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.

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

Example

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

Reading contents of all files in a directory

To read the contents of all files in a particular directory, get the File objects of all files in it as an array, using the above-mentioned method and then, read contents of each file object in the array using the Scanner class and its methods.

Example

import java.io.File; import java.io.IOException; import java.util.Scanner; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\Demo"); //List of all files and directories File filesList[] = directoryPath.listFiles(); System.out.println("List of files and directories in the specified directory:"); Scanner sc = null; for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); //Instantiating the Scanner class sc= new Scanner(file); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) < input = sc.nextLine(); sb.append(input+" "); >System.out.println("Contents of the file: "+sb.toString()); System.out.println(" "); > > >

Output

List of files and directories in the specified directory: File name: samplefile1.txt File path: D:\Demo\samplefile1.txt Size :262538260480 Contents of the file: Contents of the sample file 1 File name: samplefile2.txt File path: D:\Demo\samplefile2.txt Size :262538260480 Contents of the file: Contents of the sample file 2 File name: samplefile3.txt File path: D:\Demo\samplefile3.txt Size :262538260480 Contents of the file: Contents of the sample file 3 File name: samplefile4.txt File path: D:\Demo\samplefile4.txt Size :262538260480 Contents of the file: Contents of the sample file 4 File name: samplefile5.txt File path: D:\Demo\samplefile5.txt Size :262538260480 Contents of the file: Contents of the sample file 5

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Tuesday, February 28, 2023

Read or List All Files in a Folder in Java

In this post we’ll see how to read or list all the files in a directory using Java. Suppose you have folder with files in it and there are sub-folders with files in those sub-folders and you want to read or list all the files in the folder recursively.

Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories.

Test abc.txt Test1 test.txt test1.txt Test2 xyz.txt

Java Example to read all the files in a folder recursively

There are two ways to list all the files in a folder; one is using the listFiles() method of the File class which is there in Java from 1.2.

Читайте также:  Demo program in java

Another way to list all the files in a folder is to use Files.walk() method which is a recent addition in Java 8.

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Stream; public class ListFiles < public static void main(String[] args) < File folder = new File("G:\\Test"); ListFiles listFiles = new ListFiles(); System.out.println("reading files before Java8 - Using listFiles() method"); listFiles.listAllFiles(folder); System.out.println("-------------------------------------------------"); System.out.println("reading files Java8 - Using Files.walk() method"); listFiles.listAllFiles("G:\\Test"); >// Uses listFiles method public void listAllFiles(File folder)< System.out.println("In listAllfiles(File) method"); File[] fileNames = folder.listFiles(); for(File file : fileNames)< // if directory call the same method again if(file.isDirectory())< listAllFiles(file); >else < try < readContent(file); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > > // Uses Files.walk method public void listAllFiles(String path) < System.out.println("In listAllfiles(String path) method"); try(Streampaths = Files.walk(Paths.get(path))) < paths.forEach(filePath -> < if (Files.isRegularFile(filePath)) < try < readContent(filePath); >catch (Exception e) < // TODO Auto-generated catch block e.printStackTrace(); >> >); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> public void readContent(File file) throws IOException < System.out.println("read file " + file.getCanonicalPath() ); try(BufferedReader br = new BufferedReader(new FileReader(file)))< String strLine; // Read lines from the file, returns null when end of stream // is reached while((strLine = br.readLine()) != null)< System.out.println("Line is - " + strLine); >> > public void readContent(Path filePath) throws IOException < System.out.println("read file " + filePath); ListfileList = Files.readAllLines(filePath); System.out.println("" + fileList); > >
reading files before Java8 - Using listFiles() method In listAllfiles(File) method read file G:\Test\abc.txt Line is - This file is in Test folder. In listAllfiles(File) method read file G:\Test\Test1\test.txt Line is - This file test is under Test1 folder. read file G:\Test\Test1\test1.txt Line is - This file test1 is under Test1 folder. In listAllfiles(File) method read file G:\Test\Test2\xyz.txt Line is - This file xyz is under Test2 folder. ------------------------------------------------- reading files Java8 - Using Files.walk() method In listAllfiles(String path) method read file G:\Test\abc.txt [This file is in Test folder.] read file G:\Test\Test1\test.txt [This file test is under Test1 folder.] read file G:\Test\Test1\test1.txt [This file test1 is under Test1 folder.] read file G:\Test\Test2\xyz.txt [This file xyz is under Test2 folder.]

Here we have two overloaded listAllFiles() methods. First one takes File instance as argument and use that instance to read files using the File.listFiles() method. In that method while going through the list of files under a folder you check if the next element of the list is a file or a folder. If it is a folder then you recursively call the listAllFiles() method with that folder name. If it is a file you call the readContent() method to read the file using BufferedReader.

Another version of listAllFiles() method takes String as argument. In this method whole folder tree is traversed using the Files.walk() method. Here again you verify if it is a regular file then you call the readContent() method to read the file.

Note that readContent() method is also overloaded one takes File instance as argument and another Path instance as argument.

If you just want to list the files and sub-directories with in the directory then you can comment the readContent() method.

That’s all for this topic Read or List All Files in a Folder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

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