Java File Search - Full Java Code - How to search a directory for files based on name, type and size using the FileFilter interface?
Java File Search - Full Java Code - How to search a directory for files based on name, type and size using the FileFilter interface?
This article is part of a tutorial.
Tutorial Index page - Java File Search
/** * $Id: FilterFiles.java 77 2010-02-15 16:25:39Z oneyour $ * * This is an accompanying program for the article * <a href="http://www.1your.com/drupal/filterfilesinJava " title="http://www.1your.com/drupal/filterfilesinJava ">http://www.1your.com/drupal/filterfilesinJava </a> * * Copyright (c) 2009 - 2010 <a href="http://www.1your.com" title="www.1your.com">www.1your.com</a>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of <a href="http://www.1your.com" title="www.1your.com">www.1your.com</a> nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.util.Scanner; /** * A Java Program to search for files within a specified directory. Currently * three types of filtering are supported. * 1. Filter by extension (Type) * 2. Filter by size * 3. Filter by file name */ public class FilterFiles { public static final int SIZE_GREATER_THAN = 1; public static final int SIZE_LESSER_THAN = 2; public static final int SIZE_EQUAL_TO = 3; /** * Private Constructor as this is a utility class with only public * static methods */ private FilterFiles() {} /** * This main method will demonstrate the functionality offered by this class. * * It will do the following: * 1. Get the path to the directory where the searching will be done from the user * 2. Get the type of search from the user * 3. Depending on the type of search, get the required search values from the user * 4. Perform the search * 5. List the search results back to the user */ public static void main(String[] args) { // Request and read user input // -- the folder name/path from where the list of files will be retrieved // -- the type of filtering // ------ if by 'file extension' then read the set of filter extensions // ------ if by 'file name' then read the filter name text // ------ if by 'file size' then read the filter file size and the comparison operator // Note: Should validate the command line input to make sure it is a valid and not empty. // This validation is not implemented in this program. // Get the containing the directory path String inputMessage = "Enter the name/path of the folder: "; String folderName = readCommandLineInput(inputMessage); // Get the type of filtering inputMessage = "\nWhat type of filtering you want to do?\n" + "1. By file Extension\n" + "2. By file Name\n" + "3. By file Size\n " + "(Just enter the number of the filter type)"; String filterType = readCommandLineInput(inputMessage); // Depending on the type of filtering, get the respective filter values File[] files = null; switch(Integer.parseInt(filterType)) { case 1: inputMessage = "Enter the file extensions (comma seperated if more than one) :\n" + "(The file search will find the files of these specified extensions)"; String commaSepExtensions = readCommandLineInput(inputMessage); String[] filterExtensions = commaSepExtensions.split(","); FilenameFilter fileTypeFilter = createFileTypeFilter(filterExtensions); files = FilterFiles.listFiles(folderName, fileTypeFilter); break; case 2: inputMessage = "Enter the file name search text :\n" + "(The file search will find the files that contains this text in its file name)"; String fileNameText = readCommandLineInput(inputMessage); FilenameFilter fileNameFilter = createFileNameFilter(fileNameText); files = FilterFiles.listFiles(folderName, fileNameFilter); break; case 3: inputMessage = "Please specify operation criteria do you want to use in the file size search:\n" + "1. Greater Than (>)\n" + "2. Less Than (<)\n" + "3. Equal To (=)\n" + "(Just enter the number of the operation)"; String fileSizeComparisonText = readCommandLineInput(inputMessage); int fileSizeComparisonOperator = Integer.parseInt(fileSizeComparisonText); inputMessage = "Enter the search file size (in bytes):\n" + "(The file search will find the files whose size is >, < or = to this file size.)"; String fileSizeText = readCommandLineInput(inputMessage); FileFilter fileSizeFilter = createFileSizeFilter(Long.parseLong(fileSizeText), fileSizeComparisonOperator); files = FilterFiles.listFiles(folderName, fileSizeFilter); break; } if (files != null) { // Print them out in the console System.out.println("List of filtered files are:"); for (File file: files) { System.out.println(file); } } else { System.out.println("No files in folder: " + folderName); } } /********************* Utility Methods *********************/ /** * Request and read input from the command line (System.in) * * @param inputMessage * The message to be displayed as a request to the user * * @return * The input from the command line * * @throws IOException * Any problems while reading the input */ public static String readCommandLineInput(String inputMessage) { System.out.println(inputMessage); Scanner scanner = new Scanner(System.in); String inputLine = scanner.nextLine(); return inputLine; } /********************* List File Methods *********************/ /** * Find all the files within the specified directory using the * supplied FilenameFilter as a filter * * @param dirPath * The path to the directory containing the files. * * @param filter * This FilenameFilter will be used when listing the files * * @return * The files within the specified directory filtered using the * supplied FilenameFilter filter. */ public static File[] listFiles(String dirPath, FilenameFilter filter) { File dir = new File(dirPath); if (dir.exists()) { return dir.listFiles(filter); } return null; } /** * Find all the files within the specified directory using the * supplied FileFilter as a filter * * @param dirPath * The path to the directory containing the files. * * @param filter * This FileFilter will be used when listing the files * * @return * The files within the specified directory filtered using the * supplied FileFilter filter. */ public static File[] listFiles(String dirPath, FileFilter filter) { File dir = new File(dirPath); if (dir.exists()) { return dir.listFiles(filter); } return null; } /********************* Create Filter Methods *********************/ /** * Creates a new FilenameFilter which will filter the files with the specified * extensions. * * @param extensions * An array of file extensions that will be used for the filtering. * i.e. Any file with the specified extensions will remain after the filtering. * * @return * A FilenameFilter that will filter files with the specified file extensions */ public static FilenameFilter createFileTypeFilter(final String[] extensions) { FilenameFilter fileNameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { for (String extension: extensions) { if (name.endsWith(extension.trim())) { return true; } } return false; } }; return fileNameFilter; } /** * Creates a new FilenameFilter which will filter the files containing * the specified search text in its file name. * * @param titleSearchText * The text that will used for the filtering. i.e. Any file that contains * this text in its file name will remain after the filtering. * * @return * A FilenameFilter that will filter files containing the specified text in * its file name */ public static FilenameFilter createFileNameFilter(final String titleSearchText) { FilenameFilter fileNameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { int extensionStartPosition = name.indexOf('.'); if (name.substring(0, extensionStartPosition) .toLowerCase().contains(titleSearchText.trim().toLowerCase())) { return true; } return false; } }; return fileNameFilter; } /** * Creates a new FileFilter which will filter the files based on its file size. * * @param fileSizeInBytes * The size in bytes to use for the filtering * * @param operation * The operation to be applied along with the fileSizeInBytes to the size of * the files. Check the public static variables defined in this class. * * @return * A FileFilter that will filter files based on the specified file size and * the operation */ public static FileFilter createFileSizeFilter(final long fileSizeInBytes, final int operation) { FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File pathname) { switch (operation) { case SIZE_GREATER_THAN: if (pathname.length() > fileSizeInBytes) { return true; } return false; case SIZE_LESSER_THAN: if (pathname.length() < fileSizeInBytes) { return true; } return false; case SIZE_EQUAL_TO: if (pathname.length() == fileSizeInBytes) { return true; } return false; } return false; } }; return fileFilter; } } // End of class
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
