Search code examples
javaiofile-attributes

Java I/O: Setting time stamp


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?


Solution

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