7

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.

Metadata
  • 2,127
  • 9
  • 56
  • 127

2 Answers2

4

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
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
4
// 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
E_net4
  • 27,810
  • 13
  • 101
  • 139
Charlie 木匠
  • 2,234
  • 19
  • 19