Read Unknown File Names from Directory

I would like to read a file from a directory. In this directory there are eight additional files with the same extension (.csv). Likewise, the file name is not directly known. The name of the file looks like this:

test_file_1_2017_06_24.csv

It can change however, if I call the directory the next day . Then the file name is:

test_file_2_2017_06_25.csv or test_file_1_2017_06_25.

The name of the file and the date change. Is there a way to read the file "variable" in Java or to read the file but don´t know the exactly name? The directory is always the same ("H:/) (After the file read, then the file respectively the resulting string is furtherprocessed with split() ). Thanks for helpfull answers!

Edit: Read the directory and shows only csv-Files

File dir = new File("H:/");

    File[] fileArray = dir.listFiles(new FilenameFilter() {  

        public boolean accept(File dir, String name) {
            return name.endsWith(".csv");
        }
    });
    for(File f: fileArray){
        System.out.println(f.getName());
    }
5

2 Answers

File directory = new File("H:/");

File[] allFilesInDir = directory.listFiles();

See ().

You can also provide a FilenameFilter to get only .csv files:

File[] allCsvFiles = directory.listFiles( new FilenameFilter() {
  public boolean accept(File dir, String name) {
    if ( name.toUpperCase().endsWith(".CSV") ) {
      return new File(dir,name).isFile(); // Make sure we don't accept sub-directories ending in .csv
    }
  }
});
4

You can use the following code to go through a folder, check for csv files and work with it. Hope it helps.

File folder = new File("H:/"); /*path to your folder*/
    String[] filesPresent = folder.list();
    if(filesPresent.length==0){
        System.out.println("Nothing to delete");
    }else{
        for(String fileName : filesPresent){  // looping through files in the directory
            if(fileName.toLowerCase().endsWith(".csv") && (new File(fileName).isFile())){
                //this is a csv file.
                //you can do your operations here
                File file = new File(fileName);
                //now you can do any file operations required with the file object
            }
        }
    }
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest