Java I/O: Setting time stamp

Viewed 61

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?

3 Answers

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.

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

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);`
Related