Get Metadata of file in Java - getFileSize(), getLastModified(), setLastModified()

Metadata of file in Java can be obtained using File class methods:
length() - for getting size of file (In bytes)
lastModified() - get last modified time of  file in milliseconds( long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970))
setLastModified(long time) - set last modified time of a file 

Below sample program shows uses these file methods and display size/last modified time. I have executed this program in Ubuntu. It will work in windows slight modification(uncomment File object creation code in Windows and comment current one) 
import java.text.SimpleDateFormat;
import java.util.Calendar;

 * @author devinline
public class FindMetaData {

 public static void getLastModifiedDate(File file) {

  SimpleDateFormat dateFormatter = new SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss");
  System.out.println("last modified time of file is "
    + dateFormatter.format(file.lastModified()));

 public static void setLastModifiedDate(File file) {
  Calendar calendar = Calendar.getInstance();
  System.out.println("Call getModifiedtime method again "
    + "after making today's date as moified date ");

 public static void getFileSize(File file) {
  System.out.println("File Size in bytes and kilo bytes are:: "
    + file.length() + " bytes\tand " + (file.length() / 1024)
    + " Kilobytes");

 public static void main(String[] args) {
   * In Windows we can have File file = new File(
   * "E:\\org.jacoco.agent-");
  File file = new File(

  // get file size
  // get last modified
  // set last modified and disply agian modified date


=======Sample output===========
File Size in bytes and kilo bytes are:: 286862 bytes and 280 Kilobytes
last modified time of file is 2012-02-09 02:03:45
Call getModifiedtime method again after making today's date as moified date
last modified time of file is 2013-10-10 06:10:12


Previous Post Next Post