2

I'm reading Oracle documentation and encountered something that looks like an error to me.

Perhaps someone can confirm, or explain it better than the documentation.

Source: https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html

Code:

Path file = ...;
BasicFileAttributes attr =
    Files.readAttributes(file, BasicFileAttributes.class);
long currentTime = System.currentTimeMillis();
FileTime ft = FileTime.fromMillis(currentTime);
Files.setLastModifiedTime(file, ft);

Should not setLastModifiedTime() be called on attr instead of Files? (attr.setLastModifiedTime(file, ft))

If not, why is attr needed at all?

  • `Files` is the class that reads the attributes, so it should also be the one that writes them. It's just a convenient way to do common file operations without interacting with the attributes. `attr` (and indeed its class `BasicFileAttributes`) doesn't seem to be needed in this context, but can be useful because it provides a platform-agnostic way of grouping file properties together. – Paul Benn Nov 15 '18 at 10:38

3 Answers3

0

The internal code for this method is :

  public static Path setLastModifiedTime(Path path, FileTime time)
        throws IOException
    {
        getFileAttributeView(path, BasicFileAttributeView.class)
            .setTimes(time, null, null);
        return path;
    }

As you can see it fetches the attribute using getFileAttributeView() and then set the Time on that.

This method is just a convenience API provided in the Files class.

akshaya pandey
  • 997
  • 6
  • 16
0

BasicFileAttributes is for getting the basic attributes for many filesystem and it doesn't defined any modification methods. So to modify the LastModifiedTime you have to use the method which is defined in the Files class.

FYI: Files

mallikarjun
  • 1,862
  • 5
  • 23
  • 47
0

You are right, attr is unused in this specific snippet, it seems as a copy paste of same code for different snippets,

Because the context of snippets is Basic File Attributes

Before and after the sample, other snippets use attr, as:

System.out.println("size: " + attr.size());  

System.out.println("isReadOnly is " + attr.isReadOnly());

So in this snippet you can remove unused assignment line

BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);`
Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233