File modified time

In this chapter you will learn:

  1. How to get the file last modified time
  2. How to change last-modified time

Get the file last modified time

long lastModified() returns the time that the file denoted by this abstract pathname was last modified.

The return value is a long type which is not user friendly. We can pass the long value to a Date type and then output meaningful result.

import java.io.File;
import java.util.Date;
//from   j  av a  2 s  .  co m
public class Main {

  public static void main(String[] args) {
    File aFile = new File("c:/");
    System.out.println(aFile.lastModified());
    System.out.println(new Date(aFile.lastModified()));

  }
}

The output:

1288796519357
Wed Nov 03 08:01:59 PDT 2010

Change last-modified time

boolean setLastModified(long time) Sets the last-modified time of the file or directory named by this abstract pathname.

The time value is in long type. We can create a Date object and get the long value from it.

import java.io.File;
import java.util.Date;
//from   j a v a2 s.c o  m
public class Main {

  public static void main(String[] args) {
    File file = new File("c:/a.htm");
    file.setLastModified(new Date().getTime());

    
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to know if a file is executable, readable or writable
  2. Change a file to executable, readable, writable