Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get creation date of a file using Scala

Tags:

scala

One of the requirements in my project needs to check if the file's creation date and determine if it is older than 2 days from current day. In Java, there is something like below code which can get us the file's creation date and other information.

Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

But I don't know how to write the same code in Scala. Could anyone let me know how the same can be implemented in Scala.

like image 606
Metadata Avatar asked Nov 23 '17 10:11

Metadata


1 Answers

Java

The preferred way to do this is using the newer java.nio.file API:

import java.nio.file.*;

You can access the modified time (along with much else) in Files:

FileTime modified = Files.getLastModifiedTime(path)

This gives you a FileTime, which may be converted to a java.time.Instant

Instant modifiedInstant = modified.toInstant();

You can then do this, with:

import java.time.temporal.ChronoUnit.DAYS;

boolean isMoreThan2DaysOld = modifiedInstant.plus(2, DAYS).isBefore(Instant.now())

Scala

All of this is accessible from scala (unless you are using ScalaJS):

import java.nio.file._; import java.time._; import java.time.temporal.ChronoUnit.DAYS
val isMoreThan2DaysOld 
  = Files.getLastModifiedTime(path).toInstant.plus(2, DAYS) isBefore Instant.now
like image 86
oxbow_lakes Avatar answered Sep 17 '22 07:09

oxbow_lakes