Java File setLastModified() Method Detailed Explanation

Java File Java File


setLastModified()is a method in Javajava.io.Fileprovided by the File class, used to set the last modified time of a file or directory.

Method Syntax

public boolean setLastModified(long time)

Method Parameters

time parameter

  • Type:long
  • Meaning: Represents the number of milliseconds since January 1, 1970, 00:00:00 GMT (i.e., the Unix timestamp)
  • Notes:
    • If the time passed in is negative, the method will throw an exceptionIllegalArgumentException
    • Time precision depends on the underlying file system support (some systems may only be accurate to the second)

Return Value

  • Return type:boolean
  • true: Indicates that the file's last modified time was set successfully.
  • false: Indicates that the operation failed, possibly because the file does not exist, there is no write permission, or the file system does not support this operation.

Usage Examples

Basic Usage

Example

import java.io.File;

public class FileTimeExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
       
        // Get the current time as the new modification time
        long newTime = System.currentTimeMillis();
       
        // Set the file's last modified time
        boolean success = file.setLastModified(newTime);
       
        if (success) {
            System.out.println("File modification time updated successfully");
        } else {
            System.out.println("File modification time update failed");
        }
    }
}

Setting a Specific Date

Example

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SpecificDateExample {
    public static void main(String[] args) throws Exception {
        File file = new File("report.doc");
       
        // Create a specific date (January 1, 2023)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date specificDate = sdf.parse("2023-01-01");
       
        // Convert to millisecond timestamp
        long timeInMillis = specificDate.getTime();
       
        // Set the file modification time
        if (file.setLastModified(timeInMillis)) {
            System.out.println("Successfully set the file modification time to January 1, 2023");
        }
    }
}

Notes

  1. File existence check: Before calling this method, you should first check whether the file exists
  2. Permission issues: Ensure the program has sufficient permissions to modify the target file
  3. File system limitations: Some file systems may not support precise time settings
  4. Time precision: Different operating systems may have different support for time precision
  5. Symbolic links: If the file is a symbolic link, this method will affect the actual file the link points to

FAQ

Why does setLastModified() return false?

Possible reasons include:

  • The file does not exist
  • No write permission
  • The file system does not support modifying the timestamp
  • The passed time parameter is invalid

How to ensure the time setting is successful?

Recommended check steps:

  1. Check if the file exists:file.exists()
  2. Check if there is write permission:file.canWrite()
  3. CallsetLastModified()then check the return value
  4. Callfile.lastModified()to verify whether the time has been updated

Does this method affect the file's creation time?

No.setLastModified()It only affects the last modified time, not the file's creation time. In the standard Java API, there is no direct method to modify a file's creation time.


Practical Application Scenarios

  1. File backup system: Keep the original file timestamps when restoring backups
  2. Test environment: Simulate file modification time to test time-related business logic
  3. File synchronization tools: Keep the timestamps of the source and target files consistent
  4. Archiving system: Set a uniform modification time for archived files

By mastering thesetLastModified()method, you can handle file time-related operations more flexibly and add more practical functionality to your Java file processing programs.

Java File Java File

Other Extensions