How to check file name contain any date in it name in Java?

Tags:



I need to check a filename contain any date or number in its name and if it contain to change the name accordingly.

Example 1

phd_20001_pat_apr.txt.gz

In above example filename contain 20001. So i want to change it accordingly-

phd_*_pat_apr*

example2

phd_pat_mnc.txt.gz

In above example no date or number present in filename. So it won’t be change.

Could you please tell me what are the changes I do in the below code to get the desirable output-

filename & source_file_nm are header.

if ( (((java.util.List<String>)globalMap.get("filename")).get(i)).contains("enc_prov") )
                                      {
    globalMap.put("source_file_nm",(((java.util.List<String>)globalMap.get("filename")).get(i)).substring(0,(((java.util.List<String>)globalMap.get("filename")).get(i)).lastIndexOf("_")+2));
}             

Answer

You can use regex for that

String filenamePattern = "phd_[0-9]+_.*"
 try (Stream<Path> stream = Files.find(folder,
                                              Integer.MAX_VALUE,
                                              (path,
                                               basicFileAttributes) -> path.toFile().getName().matches(filenamePattern))) {
            return stream.collect(Collectors.toList());
        }

This will return a List of all files matching filenamePattern. Change the [maxDepth the maximum number of directory levels to search] on files.find accordingly.



Source: stackoverflow