How to get the file from the folder based on date in java -


i have multiple files in folder naming convention

name_morename_ddmmyyyy_somenumber_hhmmss.txt 

how can file has oldest date , time (i.e. oldest ddmmyyyy , hhmmss).

for in following example:

name_morename_22012012_somenumber_072334.txt name_morename_22012012_somenumber_072134.txt name_morename_24012012_somenumber_072339.txt name_morename_22012012_somenumber_072135.txt 

... oldest file be

name_morename_22012012_somenumber_072134.txt 

first, read file names list<string>.

then sort list using comparator understands format of file name:

public class filenamecomparator implements comparator<string> {      private static pattern pattern = pattern.compile("^.*?_([0-9]{2})([0-9]{2})([0-9]{4})_.*?_([0-9]{2})([0-9]{2})([0-9]{2})\\.txt$");     private static int[] grouporder = new int[]{3, 2, 1, 4, 5, 6};      @override     public int compare(string filename1, string filename2) {         matcher matcher1 = pattern.matcher(filename1);         matcher matcher2 = pattern.matcher(filename2);          return comparematchers(matcher1, matcher2);     }      private int comparematchers(matcher matcher1, matcher matcher2) {         if (matcher1.matches()) {             if (matcher2.matches()) {                  // each group in correct order (year, month, date, hour, minute, second)                 (int group : grouporder) {                     int result = comparevalues(matcher1.group(group), matcher2.group(group));                     if (result != 0) {                         return result;                     }                 }                  return 0;              } else {                 // filename 2 incorrect pattern                 return -1;             }         } else {             // filename 1 incorrect pattern             return 1;         }     }      private int comparevalues(string value1, string value2) {         return new integer(value1).compareto(new integer(value2));     } } 

to sort:

list<string> filenames = ...; /* populate list of filenames */ collections.sort(filenames, new filenamecomparator()); 

to oldest, take first one. youngest, take last one.

edit: if updated file name pattern is:

if-logfile_2016_jun_02_115011.txt 

... regular expression , code need change able extract parameters , perform correct comparison. regex be:

^.*?_([0-9]{4})_(.{3})_([0-9]{2})_([0-9]{2})([0-9]{2})([0-9]{2})\\.txt$ 

... , process them in order (1, 2, 3, 4, 5, 6) , when process second group, need compare in month name order.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -