Tuesday, 24 October 2023

Write a java program to display the files having extension .txt from a given directory. -Core Java Slip8

 

Write a java program to display the files having extension .txt from a given directory.    

import java.io.File;

 

public class ListTxtFiles {

    public static void main(String[] args) {

        // Specify the directory path where you want to search for .txt files

        String directoryPath = "C:/Program Files/Java/jdk1.7.0_80/bin";  // Replace with your directory path

 

        File directory = new File(directoryPath);

 

        if (directory.exists() && directory.isDirectory()) {

            File[] files = directory.listFiles();

 

            if (files != null) {

                System.out.println("List of .txt files in the directory:");

 

                for (File file : files) {

                    if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) {

                        System.out.println(file.getName());

                    }

                }

            } else {

                System.out.println("No files found in the directory.");

            }

        } else {

            System.out.println("The specified directory does not exist or is not a directory.");

        }

    }

}

 

Output

 

C:\Program Files\Java\jdk1.7.0_80\bin>javac ListTxtFiles.java

 

C:\Program Files\Java\jdk1.7.0_80\bin>java ListTxtFiles

List of .txt files in the directory:

a.txt

b.txt