Slip No.8
B) Write a java program to display the files having extension .txt from a given directory.1. Open Notepad.
2. Type the following code:
-
import java.io.File;
import java.io.FilenameFilter;
import java.util.Scanner;
public class TxtFileLister {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the directory path from the user
System.out.print("Enter the directory path: ");
String directoryPath = scanner.nextLine();
// Create a File object for the directory
File directory = new File(directoryPath);
// Check if the directory exists and is a directory
if (!directory.exists() || !directory.isDirectory()) {
System.out.println("The provided path is not a valid directory.");
scanner.close();
return;
}
// Create a FilenameFilter to filter .txt files
FilenameFilter textFileFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
// Get the list of .txt files in the directory
String[] txtFiles = directory.list(textFileFilter);
// Check if there are any .txt files
if (txtFiles == null || txtFiles.length == 0) {
System.out.println("No .txt files found in the directory.");
} else {
System.out.println(".txt files in the directory:");
for (String fileName : txtFiles) {
System.out.println(fileName);
}
}
scanner.close();
}
}
4. Compile the Java program by typing:
javac TxtFileLister.java
5. Run the compiled Java program by typing:
java TxtFileLister
No comments:
Post a Comment