Search for Text Files in Directory

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to search for text files in a directory using Java. This project will guide you through the process of getting the input path from the user, validating the input, finding all the text files in the directory, and printing their names.

👀 Preview

Please enter the read path:/home/labex/project/files
Found text files:
file1.txt
file3.txt
file6.txt

🎯 Tasks

In this project, you will learn:

  • How to use the Scanner class to get user input for the directory path
  • How to validate the input path using the File class
  • How to create a custom FilenameFilter to filter text files
  • How to use the listFiles() method to find all the text files in the directory
  • How to iterate through the found text files and print their names

🏆 Achievements

After completing this project, you will be able to:

  • Obtain user input for a directory path using the Scanner class
  • Validate the input path using the File class
  • Implement a custom FilenameFilter to filter text files
  • Utilize the listFiles() method to retrieve all text files in a directory
  • Iterate through the found text files and print their names

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/ConcurrentandNetworkProgrammingGroup(["`Concurrent and Network Programming`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/method_overriding("`Method Overriding`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/ConcurrentandNetworkProgrammingGroup -.-> java/working("`Working`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/method_overriding -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/scope -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/annotation -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/inner_classes -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/classes_objects -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/class_methods -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/modifiers -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/oop -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/packages_api -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/user_input -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/files -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/identifier -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/working -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/arrays -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/comments -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/data_types -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/if_else -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/operators -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/output -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/strings -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/variables -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/string_methods -.-> lab-300396{{"`Search for Text Files in Directory`"}} java/system_methods -.-> lab-300396{{"`Search for Text Files in Directory`"}} end

Get the Input Path

In this step, you will learn how to use the Scanner class to get the specified path from the user.

  1. Open the SelectTxtFile.java file in your code editor.
  2. In the main method, create a new Scanner object to read user input:
Scanner scanner = new Scanner(System.in);
  1. Display a prompt message to the user asking for the read path:
System.out.print("Please enter the read path:");
  1. Use the nextLine() method to read the user's input and store it in the path variable:
String path = scanner.nextLine();
  1. After reading the input, close the Scanner to release the resources:
scanner.close();

Validate the Input Path

In this step, you will learn how to use the File class to check if the input path is a valid directory.

  1. Create a new File object with the user-provided path:
File directory = new File(path);
  1. Use the exists() method to check if the directory exists:
if (!directory.exists() || !directory.isDirectory()) {
  1. If the directory does not exist or is not a directory, print an error message and exit the program:
    System.out.println("The directory does not exist, or it is not a directory");
    return;
}

Find Text Files in the Directory

In this step, you will learn how to use a FilenameFilter to find all the text files in the directory.

  1. Create a new TxtFileFilter class that implements the FilenameFilter interface:
static class TxtFileFilter implements FilenameFilter {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
}
  1. Use the listFiles() method of the File class to get an array of files in the directory, filtering them with the TxtFileFilter:
File[] files = directory.listFiles(new TxtFileFilter());

Print the Found Text Files

In this final step, you will learn how to iterate through the found text files and print their names.

  1. Print a header to indicate that text files have been found:
System.out.println("Found text files:");
  1. Use a for-each loop to iterate through the files array and print the name of each file:
for (File file : files) {
    System.out.println(file.getName());
}

That's it! You have now completed the project of searching for text files in a directory. You can test your program by running the SelectTxtFile class.

In this step, we will verify the file search Java program.

  1. Open your terminal and compile the Java file using the javac command:
javac SelectTxtFile.java
  1. After successfully compiling the Java file, execute the compiled program using the java command:
java SelectTxtFile
  1. Upon running the Java program, you'll be prompted to enter the read path. Provide the directory path where the text files are located and press Enter.
  • If the directory does not exist or is not a directory, you'll receive a message indicating the issue.
  • If the directory is valid and contains text files, the program will display the names of the text files found in that directory.

Here's an example of expected output:

Please enter the read path:/home/labex/project/files
Found text files:
file1.txt
file3.txt
file6.txt

By following these steps, you can verify the functionality of the Java program for selecting text files.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like