简体   繁体   中英

read single file type from directory containing multiple file types java

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);
        }
    }
}

This code will return every file matching the given extension (in your case .csv ):

public static List<File> getFiles(String extension, final File folder)
{

    extension = extension.toUpperCase();

    final List<File> files = new ArrayList<File>();
    for (final File file : folder.listFiles())
    {

        if (file.isDirectory())
            files.addAll(getFiles(extension, file));
        else if (file.getName().toUpperCase().endsWith(extension))
            files.add(file);

    }

    return files;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM