
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to change the last modification time of a file in Java
Problem Description
How to change the last modification time of a file?
Solution
This example shows how to change the last modification time of a file with the help of fileToChange.lastModified() and fileToChange setLastModified() methods of File class .
import java.io.File; import java.util.Date; public class Main { public static void main(String[] args) throws Exception { File fileToChange = new File ("C:/myjavafile.txt"); fileToChange.createNewFile(); Date filetime = new Date (fileToChange.lastModified()); System.out.println(filetime.toString()); System.out.println (fileToChange.setLastModified (System.currentTimeMillis())); filetime = new Date (fileToChange.lastModified()); System.out.println(filetime.toString()); } }
Result
The above code sample will produce the following result.The result may vary depending upon the system time.
Sat Oct 18 19:58:20 GMT+05:30 2008 true Sat Oct 18 19:58:20 GMT+05:30 2008
The following is another sample example of last modification time of a file in java
import java.io.File; import java.text.SimpleDateFormat; public class GetFileLastModifiedExample { public static void main(String[] args) { File f1 = new File("C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\abc.png"); System.out.println("Before Format : " + f1.lastModified()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println("After Format : " + sdf.format(f1.lastModified())); } }
The above code sample will produce the following result. The result may vary depending upon the system time.
Before Format : 1473659371467 After Format : 09/12/2016 11:19:31
java_files.htm
Advertisements