Practical Examples
File Change Detection
public class FileChangeMonitor {
public static boolean hasFileChanged(Path filePath, long lastCheckedTime) {
try {
long currentModificationTime = Files.getLastModifiedTime(filePath).toMillis();
return currentModificationTime > lastCheckedTime;
} catch (IOException e) {
System.err.println("Error checking file modification");
return false;
}
}
}
Backup Strategy Implementation
public class FileBackupUtility {
public static void backupIfModified(Path source, Path backup) throws IOException {
FileTime sourceModifiedTime = Files.getLastModifiedTime(source);
FileTime backupModifiedTime = Files.exists(backup)
? Files.getLastModifiedTime(backup)
: null;
if (backupModifiedTime == null || sourceModifiedTime.compareTo(backupModifiedTime) > 0) {
Files.copy(source, backup, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Backup created: " + backup);
}
}
}
Timestamp-Based File Synchronization
graph TD
A[Check Source File] --> B{Compare Timestamps}
B -->|Newer| C[Copy/Update Destination]
B -->|Older| D[Skip File]
Logging File Modifications
public class FileModificationLogger {
public static void logFileChanges(Path directory) throws IOException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
directory.register(watchService,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
Path changedPath = (Path) event.context();
System.out.println("Event type: " + event.kind() +
" File affected: " + changedPath);
}
key.reset();
}
}
}
}
Common Use Cases
Scenario |
Timestamp Usage |
Purpose |
Caching |
Compare modification times |
Validate cache freshness |
Backup Systems |
Track file changes |
Incremental backup |
File Synchronization |
Compare timestamps |
Detect updates |
- Cache timestamp results
- Use NIO.2 methods for efficiency
- Minimize file system calls
At LabEx, we emphasize practical, efficient file timestamp management techniques that solve real-world programming challenges.