简体   繁体   中英

how to extract date from the given filename in java

I have my file names as below

  1. C:\\Users\\name\\Documents\\repository\\zzz\\xxx_yyy\\new\\aaa_bbb_ccc_ddd_eee_ZZ_E_20160801_20160831_v1-0.csv
  2. C:\\Users\\name\\Documents\\repository\\zzz\\xxx_yyy\\new\\aaa_bbb_ppp_ccc_ddd_eee_ZZ_E_20160801_20160831_v1-0.csv

I have to write a single java script for both the file format to extract both the dates from each filename.

Can you please help.

You should use Regular expressions to extract dates from filenames like these.

private static Date[] extractDatesFromFileName(File file) throws ParseException {
    Date[] dates = new Date[2];

    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");

    String regex = ".*(\\d{8})_(\\d{8}).*";
    Pattern pattern = Pattern.compile(regex);
    Matcher m = pattern.matcher(file.getName());
    if (m.find()) {
        dates[0] = dateFormatter.parse(m.group(1));
        dates[1] = dateFormatter.parse(m.group(2));
    }
    System.out.println(dates[0]);
    System.out.println(dates[1]);
    return dates;
}

Little explanation:

In regex .*(\\\\d{8})_(\\\\d{8}).* :

  • .* stands for any sing repeated from zero to unlimited times
  • (\\\\d{8}) stands for exactly eight digits (if they are in brackets they are considered capturing groups , we have 2 capturing groups in this regex, one for each date)
  • _ stands for _ sign :)

If filename matches provided pattern both dates are extracted, parsed and returned as array. You should add some error handling etc.

If you mean a Java script (not Javascript) you can use regexp, something like the following:

String in = "C:\\Users\\name\\Documents\\repository\\zzz\\xxx_yyy\\new\\aaa_bbb_ppp_ccc_ddd_eee_ZZ_E_20160801_20160831_v1-0.csv";
Pattern p = Pattern.compile("_(\\d{8})_v1-0");
Matcher m = p.matcher(in);
if (m.find()){
    System.out.println(m.group(1));
}

I think you want to extract two dates which are present in each file path. This could be done as follows:

String filename1 = "C:\\Users\\name\\Documents\\repository\\zzz\\xxx_yyy\\new\\aaa_bbb_ccc_ddd_eee_ZZ_E_20160801_20160831_v1-0.csv";
Pattern p = Pattern.compile("[0-9]{8}+_[0-9]{8}+");
Matcher m = p.matcher(filename1);
String[] dateStrArr = m.find()?m.group(0).split("_"): null;

First date will be in 0 index and second date will be in 1 index position.

Same goes for second file name. Hope this helps.

Also once extracted you can convert them to date object using SimpleDateFormat.

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