2

I'm trying to get basic file attributes using Scala, and my reference is this Java question:

Determine file creation date in Java

and this piece of code I'm trying to rewrite in Scala:

static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }

The thing I just can't figure out is this line of code..I don't understand how to pass a class in this way using scala... or why Java is insisting upon this in the first place instead of using an actual constructed object as the parameter. Can someone please help me write this line of code to function properly? I must be using the wrong syntax

val  attr = Files.readAttributes(f,Class[BasicFileAttributeView])
Community
  • 1
  • 1
LaloInDublin
  • 5,379
  • 4
  • 22
  • 26

2 Answers2

5

Try this:

def attrs(pathStr:String) = 
  Files.getFileAttributeView(
    Paths.get(pathStr), 
    classOf[BasicFileAttributes] //corrected
  ).readAttributes
LaloInDublin
  • 5,379
  • 4
  • 22
  • 26
Nyavro
  • 8,806
  • 2
  • 26
  • 33
  • 1
    I think this answer was correct before the edit. As it is, `readAttributes` is not recognized, but changing to `classOf[BasicFileAttributesView]` works. – kfkhalili Aug 24 '18 at 09:58
0

Get file creation date in Scala, from Basic Files Attributes:

// option 1,

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

val pathStr = "/tmp/test.sql"
Files.readAttributes(Paths.get(pathStr), classOf[BasicFileAttributes]).creationTime

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

// option 2,

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

val pathStr = "/tmp/test.sql"
{
  Files
    .getFileAttributeView(Paths.get(pathStr), classOf[BasicFileAttributeView])
    .readAttributes.creationTime
}

res20: java.nio.file.attribute.FileTime = 2018-03-07T19:00:19Z

Charlie 木匠
  • 2,234
  • 19
  • 19