File setLastModified() method in Java with Examples
Last Updated :
20 May, 2021
The setLastModified() method is a part of File class.The function sets the last modified time of the file or directory. The function sets the last modified value of the file in milliseconds.
Function Signature:
public boolean setLastModified(long time)
Function Syntax:
file.setLastModified(time)
Parameters: This function accepts a long value as parameter which represents the new last modified time.
Return value: The function returns a boolean value which states whether the new last modified time is set or not.
Exception; This method throws following exceptions:
- SecurityException if the function is not allowed write access to the file
- IllegalArgumentException if the argument is negative
Below programs will illustrate the use of the setLastModified() function:
Example 1: We will try to change the last modified time of a existing file in f: directory.
Java
import java.io.*;
public class solution {
public static void main(String args[])
{
try {
File f = new File( "f:\\program.txt" );
long time = 100000000 ;
if (f.setLastModified(time)) {
System.out.println( "Last modified time is set" );
}
else {
System.out.println( "Last modified time cannot be set" );
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
|
Output:
Last modified time is set
Example 2: We will try to change the last modified time of a non existing file in f: directory.
Java
import java.io.*;
public class solution {
public static void main(String args[])
{
try {
File f = new File( "f:\\program1.txt" );
long time = 100000000 ;
if (f.setLastModified(time)) {
System.out.println( "Last modified "
+ "time is set" );
}
else {
System.out.println( "Last modified time"
+ " cannot be set" );
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
|
Output:
Last modified time cannot be set
The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...