How to get file creation date using Scala

One of the requirements in my project is to check whether the file creation date is set and determine whether it is older than 2 days from the current day. In Java, there is something like below code that can provide us with the file 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 do not know how to write the same code in Scala. Can someone tell me how the same can be implemented in Scala.

+4
source share
2 answers

Java

The preferred way to do this is to use the new API java.nio.file:

import java.nio.file.*;

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

FileTime modified = Files.getLastModifiedTime(path)

It gives you FileTimethat can be converted tojava.time.Instant

Instant modifiedInstant = modified.toInstant();

Then you can do it using:

import java.time.temporal.ChronoUnit.DAYS;

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

Scala

scala ( 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
+2

.

,

Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_152).

import java.nio.file.{Files, Paths}
import java.nio.file.attribute.BasicFileAttributes

val pathStr = "/tmp/test.sql"

Files.readAttributes(Paths.get(pathStr), classOf[BasicFileAttributes])

Files.readAttributes(Paths.get(pathStr), classOf[BasicFileAttributes]).creationTime

res3: java.nio.file.attribute.FileTime = 2018-03-06T00: 25: 52Z

+2

Source: https://habr.com/ru/post/1689731/


All Articles