util

Search files in a directory using FutureTask example

In this example we shall show you how to search files in a directory using FutureTask. We have implemented a Class called MatchCounter, that implements the Callable Interface. It is a task that counts the files in a directory and its subdirectories that contain a given keyword. The basics of the example are shown below:

  • The example’s task, MatchCounter is configured using a File directory in which to start the search, a String representing the keyword to look for and returns an integer counter of the number of files that contained the specific keyword.
  • MatchCounter‘s call() method performs the functionality described above. It checks the files listed in the given directory for the specific keyword and sums the accourances found. In case there are sub-directories (isDirectory() API method of File) we create a new FutureTask and execute the same Callable (MatchCounter) for the specific subdirectory.
  • For each task a Thread is created to run it.
  • Last but not least a helper method is implemented, so as to actually search the contents of a file for a specific keyword. It is invoked by the call() method of the MatchCounter task. For each line of the file (nextLine() API method of the Scanner) it checks if it contains the specific keyword (contains(CharSequence s) API method of the String) and returns true if the keyword exists.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class FutureTest {


    public static void main(String[] args) {

  

  Scanner input = new Scanner(System.in);

  

  System.out.print("Please enter directory (e.g. /usr/local/jdk7.0/src): ");

  

  String dir = input.nextLine();

  

  System.out.print("Please enter keyword (e.g. myFile): ");

  

  String keyword = input.nextLine();


  MatchCounter countFiles = new MatchCounter(new File(dir), keyword);

  FutureTask<Integer> tsk = new FutureTask<Integer>(countFiles);

  Thread thread = new Thread(tsk);

  thread.start();

  try {


System.out.println(tsk.get() + " matching files.");

  } catch (ExecutionException e) {


e.printStackTrace();

  } catch (InterruptedException e) {

  }
    }
}

/**
 * This task counts the files in a directory and its subdirectories that contain
 * a given keyword.
 */
class MatchCounter implements Callable<Integer> {

    /**
     * 
     * dir the directory in which to start the search
     * keyword the keyword to look for
     * 
     */
    
    private File dir;
    private String keyword;
    private int counter;
    
    public MatchCounter(File directory, String keyword) {

  this.dir = directory;

  this.keyword = keyword;
    }

    public Integer call() {

  counter = 0;

  try {





File[] files = dir.listFiles();


ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();



for (File file : files) {


    if (file.isDirectory()) {



  MatchCounter counter = new MatchCounter(file, keyword);



  FutureTask<Integer> task = new FutureTask<Integer>(counter);



  results.add(task);



  Thread t = new Thread(task);



  t.start();


    } else {



  if (search(file)) {




counter++;



  }


    }


}



for (Future<Integer> result : results) {


    try {



  counter += result.get();


    } catch (ExecutionException e) {



  e.printStackTrace();


    }


}

  } catch (InterruptedException e) {

  }

  return counter;
    }

    /**
     * Searches a file for a given keyword.
     *
     *  file the file to search
     *  returns true if the keyword is contained in the file
     */
    public boolean search(File file) {

  try {


Scanner in = new Scanner(new FileInputStream(file));


boolean found = false;


while (!found && in.hasNextLine()) {


    String line = in.nextLine();


    if (line.contains(keyword)) {



  found = true;


    }


}


in.close();


return found;

  } catch (IOException e) {


return false;

  }
    }
}

 
This was an example of how to search files in a directory using FutureTask in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button