Getting a file's timestamp using ColdFusion

Finding a file's date/time is now quite easy in ColdFusion by simply making use of the underlying Java File and Date objects. A bit of code ...

<cfset filePath = "data\myfile.txt">
<cfset fileObj = createObject("java","java.io.File").init(expandPath(filePath))>
<cfset fileDate = createObject("java","java.util.Date").init(fileObj.lastModified())>

At this point the fileDate variable contains a normal ColdFusion date.

Couple of notes:

The java.io.File object gets information about the file, but does not read the file into memory. That's good.

The lastModified() method here returns a number (a 'long'), which is exactly what the java.util.Date object needs to create the Date object.

Remember not to use the variable name 'file' in your code. This appears to be a reserved name.

Comments
19 Feb 2008 02:34AM
Martin Parry said:
Many thanks - This saves doing a CFDirectory with a filter applied then faffing about with LSDateformat
12 Mar 2008 08:31PM
Suman Kar said:
You saved my life! I spent the last 4 hours trying to debug what went wrong only to land here and know 'file' is a reserved word. Thank you!
Add a comment
(will not be published)
(include http://)