Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Nov 10, 1999

What's the Time Stamp of a File?

JDK 1.1.x's java.io.File class has a lastModified():long method. You can use the value returned by lastModified method to create an instance of java.util.Date class and, thus, get a hold of date/time of last modifications for a file. Here is some sample code that prints the last modification of files in current user directory:
 
public void printCurDirContent() 
{ 
String path = "."; 
File f = new File(path); 
String[] s = f.list(); 
for(int i=0; i<s.length; i++) 
{ 
String aPath = path + "\\" + s[i]; 
File aFile = new File(aPath); 
long modified = aFile.lastModified(); 
java.util.Date d = new java.util.Date(modified); 
System.out.println(s[i]+" - "+modified+" - modified on: "+d.toString()); 
//You can also use java.util.GregorianCalendar calss 
java.util.GregorianCalendar gc = new java.util.GregorianCalendar(); 
gc.setTime(d); 
String ss = ""+gc.get(gc.YEAR)+" "+(gc.get(gc.MONTH)+1); 
ss += " "+gc.get(gc.DAY_OF_MONTH)+" "+gc.get(gc.HOUR_OF_DAY); 
ss += " "+gc.get(gc.MINUTE)+" "+gc.get(gc.SECOND); 
System.out.println(s[i]+" modified on: "+ss); 
} 
} 
JDK's documentation mentions that the return value of lastModified() method of the File class is "system-dependent and should only be used to compare with other values returned by last modified". So if you use to compare time/date stamps of files, make sure that you execute the method on your files on the same system.

As of JDK 1.2, a new method, setLastModified(:long):boolean, has been added to java.util.File class. You can use this method to change the last modification time of a file. Here is some code showing how:

 
public static void touch(String filePath) 
{ 
long timeNow = System.currentTimeMillis(); 
File f = new File(filePath); 
boolean touched = f.setLastModified(timeNow); 
if (!touched) 
{ 
System.err.println("Failed to touch: "+ filePath); 
} 
} 
Note that the return value of lastModified method and the parameter value of setLastModified(...) method are times measured in milliseconds since January 1, 1970 00:00:00 GMT.
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date