Sunday, 3 April 2016

Read multiple files of same extension at a time by Multi threading in JAVA

In this post we will tell you, how you can read all the files of a particular extension present in a directory simultaneously.
Pseudo Code:
1. Take directory and file extension as input.
2. Scan the input directory and fetch all the file present with input extension in a FILE array.
3. Create a class where we input these file's name. This class should extend THREAD class or implements RUNNABLE interface for providing multi threading features.
4. Override RUN( ) method of Thread/Runnable and read the files using wrapper of FileReader and BufferedReader. Check previous post for better understanding.

In this screenshot, you can see four text files (.txt) are present in our project directory.
Note: You can add as many as text files in this directory for reading.











Source code for this project:

1. SearchFiles.java : We will create SearchFiles's object for passing directory path and extension of file. 

import java.io.File;
public class SearchFiles {

      private   String DIR_PATH;
      private   String FILE_EXT;
     
      public SearchFiles(String dirpath,String file_extn) {
            // TODO Auto-generated constructor stub
            DIR_PATH=dirpath;
            FILE_EXT=file_extn;
      }
     
      public File[] filenames() {
           
            File dir =new File(DIR_PATH);
            if (!dir.exists()) {
                  System.out.println(DIR_PATH+ "  is not exist in your system.");
            }
            else {
                  System.out.println(DIR_PATH+ "  FOUND");
            }
            Filterfiles ff=new Filterfiles(FILE_EXT);
            File[] files=dir.listFiles(ff);

            return files;
      }}

2. Filterfiles.java : This class implements FilenameFilter interface and overrides its method accept( ) , this method is responsible for returning files with inputed extension.

import java.io.File;
import java.io.FilenameFilter;

public class Filterfiles implements FilenameFilter {

      private String fileext;
      public Filterfiles(String ext) {
            this.fileext=ext;
      }
      @Override
      public boolean accept(File dir, String name) {
            // TODO Auto-generated method stub
            return (name.endsWith(fileext));
      }

}

 3. ReadFileByThread.java : This class will call main( ) method and do what we want in this program.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileByThread extends Thread {
      File alpha;
     
      public ReadFileByThread(String filename) {
            // TODO Auto-generated constructor stub
             alpha=new File(filename);
           
      }

      public  void run() {
           
            //File alpha=new File("alpha.txt");
            try {
                  FileReader fr=new FileReader(alpha);
                  BufferedReader br=new BufferedReader(fr);
                  String line;
                  try {
                        while ((line=br.readLine())!=null) {
                              System.out.println(Thread.currentThread().getName()+": "+line);
                             
                        }
                  } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
           
      }
     
      public static void main(String[] args) {
SearchFiles sf=new SearchFiles("C:\\Users\\workspace\\Readfiles", ".txt");
            File[] allfiles=sf.filenames();
            for(File f:allfiles){
                  System.out.println(f.getName());
            }
           
            ReadFileByThread[] readfile=new ReadFileByThread[allfiles.length];
            Thread[] th=new Thread[allfiles.length];
            for (int i = 0; i < readfile.length; i++) {
                  readfile[i]=new ReadFileByThread(allfiles[i].toString());
                   th[i]=new Thread(readfile[i]);
                   th[i].start();
            }
            try {
                  Thread.sleep(5000);
            } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }}}

This code will generate one thread for one file and reads its data. Out of above program is shown below.


No comments:

Post a Comment