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.io.File;
import java.io.IOException;
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();
  file.setLastModified(calendar.getTimeInMillis());
  System.out.println("Call getModifiedtime method again "
    + "after making today's date as moified date ");
  getLastModifiedDate(file);
 }

 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-0.7.2.201409121644-runtime.jar");
   */
  File file = new File(
  "/home/zytham/Downloads/org.jacoco.agent-0.7.2.201409121644-runtime.jar");

  // get file size
  getFileSize(file);
  // get last modified
  getLastModifiedDate(file);
  // set last modified and disply agian modified date
  setLastModifiedDate(file);

 }

}
=======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
============================

2 Comments

Previous Post Next Post