开发者

File age in Java

开发者 https://www.devze.com 2023-03-12 04:56 出处:网络
I need to find the age of a file based on its name. Alle the files 开发者_Go百科keep to a naming convention like this: DD-MM-YYYY.

I need to find the age of a file based on its name. Alle the files 开发者_Go百科keep to a naming convention like this: DD-MM-YYYY.

I can make a program to come up with the filenames based on how many days/months has passed etc, using the modulus operator, but i can't seem to wrap my head around how to calculate the age from the name. Any tip is welcome.

Any codesamples/ -suggestions should preferable be in Java.

Regards Martin


You can use a DateFormat to parse a date as well as format one.

Untested:

String name = file.getName();
String datePortion = /*extract date portion*/;

DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date fileDate = fmt.parse(datePortion);
long msBetweenDates = new Date().getTime() - fileDate.getTime();

How you extract the date portion depends on your file naming scheme, but it's probably as easy as:

String datePortion = name.replaceAll(".*((\\d)+-(\\d)+-(\\d)+).*", "$1");


if the last modified date is enough, you can use:

    File file = new File("C:/file.txt");
    Date date = new Date(file.lastModified());
    System.out.println(date);
0

精彩评论

暂无评论...
验证码 换一张
取 消