File setLastModified(long) in Java

setLastModified(long): This method is available in the java.io.File class of java.

Syntax:

boolean java.io.File.setLastModified(long time)

This method takes one argument. This method sets the last-modified time of the file or directory named by this abstract pathname.

Parameters: One parameter is required for this method.

time: The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970).

Returns: true if and only if the operation succeeded; false otherwise.

Throws:

1. IllegalArgumentException - If the argument is negative.

2. SecurityException - If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String)method denies write access to the named file.

Approach 1: When no exception

Java

import java.io.File;

public class FilesetLastModified {
    public static void main(String[] args) {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);

        long time = 10000001L;

        System.out.println(file.setLastModified(time));
    }
}

Output:

true


Approach 2: IllegalArgumentException 

Java

import java.io.File;

public class FilesetLastModified {
    public static void main(String[] args) {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);

        long time = -10000001L;

        System.out.println(file.setLastModified(time));
    }
}

Output

Exception in thread "main" java.lang.IllegalArgumentException: Negative time at java.base/java.io.File.setLastModified(File.java:1441)


No comments:

Post a Comment