How to filter Text files in a directory?
- In Java, we can get all files, filter our required files from a directory using the File concept which is available in java.io package.
Demo on Filter Text files:
import java.io.File;
public class DirectoryFilesCount {
public static void main(String args[]) {
int countTextFiles = 0;
String directorypath = "D:\\path\\Files";
File directory = new File(directorypath);
File[] files = directory.listFiles();
System.out.println("<--Files in a directory-->");
for (File f : files) {
System.out.println(f.getName());
}
System.out.println("<--Text Files in a directory-->");
for (File file : files) {
if (file.getName().endsWith(".txt")) {
System.out.println(file.getName());
countTextFiles++;
}
}
System.out.println("Total number of Text files in directory=" + countTextFiles);
}
}
Filter Files |
Here we have different types of files in a directory but we can filter only Txt files and total number of txt files in a directory.
Output:
<--Files in a directory-->
File1.txt
File2.pub
File3.docx
File4.zip
File5.xlsx
File6.txt
<--Text Files in a directory-->
File1.txt
File6.txt
Total number of Text files in directory=2
Likewise as above, we can filter other type of files such as zip,pub,bat,xlsx,docx etc.,.
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.