Wednesday, 26 April 2017

Reading all files in a folder - Java Program

This post is about how to read all the files in a directory. 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.

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

Example Code

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

Another way is using 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");

     }
         
     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();
                 }
        
             }
         }
     }
         
     public void listAllFiles(String path){
         System.out.println("In listAllfiles(String path) method");
         try(Stream<Path> paths = 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);
         List<String> fileList = Files.readAllLines(filePath);
         System.out.println("" + fileList);
     }
     
}

Output

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 methods listAllFiles(). First one take File instance as argument that one is used 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.

That's all for this topic Reading all files in a folder - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Writing file in Java
  2. How to append to a file in Java
  3. How to read file from the last line in Java
  4. How to find last modified date of a file in Java
  5. Unzipping files in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment