Is it possible to read single type of file (say like CSV or txt) from the directory containing multiple file types (say like cvs , txt , doc, xml, html, etc..)
My problem is I have to provide path of the mainDirectory as an input , which further has layers of subdirectories inside it. I specifically need to read and process CSV files within these directories as I further dive in.
I am done with multiple layers of folder traversing using recursion courtesy which I have the names and total count of the files within the mainDirectory. I am also done with logic to read and CSV files. All I need to do is to get path only of CSV files and process them.
i am using below mentioned code for traversing multiple folders and getting the name :-
package org.ashu.input;
import java.io.File;
/**
*
* @author ashutosh
*/
public class MultiDir {
private int fileCount;
public void readFile(File f){
System.out.println(f.getPath());
fileCount++;
}
public void readDir(File f){
File subdir[] = f.listFiles();
for(File f_arr : subdir){
if(f_arr.isFile()){
this.readFile(f_arr);
}
if(f_arr.isDirectory()){
this.readDir(f_arr);
}
}
}
public static void main(String[] args){
MultiDir md = new MultiDir();
File mainDir = new File("/Users/ashutosh/Downloads/main_directory");
md.readDir(mainDir);
System.out.println(md.fileCount);//all file count = 1576, need to specifically get CSV
}
}
Any suggestion please.
You can simply check the extension of the file in your readDir() method. The below looks for jpg, you can use your desired extension
public void readDir(File f){
File subdir[] = f.listFiles();
for(File f_arr : subdir){
if(f_arr.isFile() && f_arr.getName().endsWith(".jpg")){
this.readFile(f_arr);
}
if(f_arr.isDirectory()){
this.readDir(f_arr);
}
}
}