Hi guys,

Hope you guys are doing great.

Today, I am going to show you how to implement a file search with a timer in Java. By ‘timer’ I mean that execution will stop after a certain time provided. You must came across this kind of functionality where the main program is stopped at a certain time limit.

Trick is simple, use the Thread and check the time limit, and if time limit is reached, interrupt the thread and exit.

First, let’s implement file search. I have used WildcardFileFilter class from Apache for regular expression implementation. FileSearchManager.java

package com.filesearch;

import java.io.File;
import java.io.FileFilter;
import java.util.LinkedList;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class FileSearchManager {

	private String inputString;
	private String directoryName;
	private File directoryObject;

	public FileSearchManager(String inputString, String directoryName) {
		this.inputString = inputString;
		this.directoryName = directoryName;
		this.directoryObject = new File(directoryName);
	}

	public Boolean directoryValidator() {
		Boolean validate = true;
		if(getDirectoryName().equalsIgnoreCase("")){
			validate = false;
		}

		if(!getDirectoryObject().isDirectory()) {
			validate = false;
		}
		return validate;		
	}

	public Boolean inputStringValidator() {
		Boolean validate = true;
		if(getInputString().equalsIgnoreCase("")) {
			validate = false;
		}
		return validate;
	}

	public void searchFile() {

		if(inputStringValidator()) {

			if(directoryValidator()) {
				try{	
					LinkedList<File> dirs = new LinkedList<File>();
					dirs.add(getDirectoryObject());					
					FileFilter filter = new WildcardFileFilter(getInputString());
					String recordCheck = "";

					while (dirs.size() > 0) {
						File dir = (File) dirs.removeLast();

						File[] matches = dir.listFiles(filter);

						if (matches != null) {
							for (int i = 0; i < matches.length; i++) {
								recordCheck +=matches[i];
								System.out.println(matches[i]);
							}
						}

						FileFilter dirFilter = new FileFilter() {
							public boolean accept(File pathname) {
								return pathname.isDirectory();
							}
						};
						File[] subDirs = dir.listFiles(dirFilter);

						if (subDirs != null) {
							for (int i = 0; i < subDirs.length; i++) {
								dirs.add(subDirs[i]);
							}
						}						
					}
					if(recordCheck.equals("")) {
						System.out.println("No records found");
						System.exit(1);
					}
				} catch (Exception exc) {
					exc.printStackTrace();
				}

			} else {
				System.err.println("Invalid Directory Path");
				System.exit(1);
			}
		}
 else {
			System.err.println("Please provide input string");	
			System.exit(1);
		}
	}

	public String getInputString() {
		return inputString;
	}

	public void setInputString(String inputString) {
		this.inputString = inputString;
	}

	public String getDirectoryName() {
		return directoryName;
	}

	public void setDirectoryName(String directoryName) {
		this.directoryName = directoryName;
	}

	public File getDirectoryObject() {
		return directoryObject;
	}

	public void setDirectoryObject(File directoryObject) {
		this.directoryObject = directoryObject;
	}
}

Next comes the Thread implementation. TimerThread.java

package com.filesearch;

public class TimerThread implements Runnable {

	FileSearchManager fileSearchManager;

	public TimerThread(String inputString, String directoryName) {
		fileSearchManager = new FileSearchManager(inputString, directoryName);
	}

	@Override
	public void run() {		
		fileSearchManager.searchFile();
	}
}

Now, the logic for interrupting the Thread based on time limit provided. TimeOutManager.java

package com.filesearch;

public class TimeOutManager {

	public void fileSearchBasedOnTimeOut(String inputString, String directoryName, long timeOut) {
		Thread taskThread = new Thread(new TimerThread(inputString, directoryName));

		taskThread.start();

		try {
			Thread.sleep(timeOut);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (taskThread.isAlive()) {			
			taskThread.interrupt();
			System.out.println("Search timeout");
			System.exit(1);
		}
	}	
}

Now, the main method. See how the parameters have been passed. StartPoint.java

package com.filesearch;

public class StartPoint {

	public static void main(String[] args) {
		new TimeOutManager().fileSearchBasedOnTimeOut("*.png", "/home/username/", 100);
	}
}

Simple, isn’t it?

I hope this post will help to those guys who are looking for only file search implementation in Java and who are looking for both file search and timer implementation.

It will be great if someone have better implementation and post the code in comment section below. Don’t worry about technology. 🙂

 

That’s it guys.

Critic/suggestions are very much welcome.

Have a great day ahead!

Loading