Sun Oct 10 2021

Searching File

File Name: search-file.java

/* Searching from directory */
import java.io.File;
import java.util.ArrayList;
import java.util.List;

class searching {
	private String fileNameToSearch;
	private List result = new ArrayList();

	public String getFileNameToSearch() {
		return fileNameToSearch;
	}

	public void setFileNameToSearch(String fileNameToSearch) {
		this.fileNameToSearch = fileNameToSearch;
	}
 
	public List getResult() {
		return result;
	}

	public void searchDirectory(File directory, String fileNameToSearch) {
		setFileNameToSearch(fileNameToSearch);
		if (directory.isDirectory())
			search(directory);
		else
			System.out.println(directory.getAbsoluteFile() + " is not a directory!");
	}

	private void search(File file) {
		if (file.isDirectory()) {
			System.out.println("Searching directory ... " + file.getAbsoluteFile());

			/* Checking file permission in directory */	
			if (file.canRead()) {
				for (File temp : file.listFiles()) {
					if (temp.isDirectory()) 
						search(temp);
					else {
						if (getFileNameToSearch().equals(temp.getName().toLowerCase()))			
							result.add(temp.getAbsoluteFile().toString());
					}
				}
			}
		}
		else
			System.out.println(file.getAbsoluteFile() + "Permission Denied"); 
	}
}
 
class searchFile { 
	public static void main(String args[]) {
		searching fileSearch = new searching();

		/* Try different directory and filename */
		fileSearch.searchDirectory(new File("/"), "abc.txt");
		int count = fileSearch.getResult().size();
		if(count ==0)
			System.out.println("\nNo result found!");
		else {
			System.out.println("\nFound " + count + " result!");
			for (String matched : fileSearch.getResult())
				System.out.println("Found : " + matched);
		}
	}
}




/* Output */
No result found!

/* ---------------------- */

Found : /home/user/Documents/abc.txt

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.