3

这两个接口有什么区别?BasicFileAttributesBasicFileAttributeView

我知道它们用于从文件中检索基本元数据,但实际上它们之间有什么不同?

编辑:我之前的意思是,在下面的示例中,两个接口可以互换使用。有什么区别吗?除了为了首先使用视图访问属性之外,您必须调用该.readAttributes()方法吗?

BasicFileAttributeView bs = Files.getFileAttributeView(path, BasicFileAttributeView.class);
        BasicFileAttributes bfa = Files.readAttributes(path, BasicFileAttributes.class);
4

1 回答 1

1

Interfaces are nothing but the signatures they describe. So the difference between these two interfaces are, that they demand methods of other signatures implemented.

If you have a BasicFileAttributeView instance, you can get a BasicFileAttributes using readAttributes(). If you don't have a BasicFileAttributeView (BFAV) instance, you can get it using Files.getFileAttributeView. It is guaranteed that you can pass BFAV, even if it may not work with every subclass of FileAttributeView.

Example:

BasicFileAttributeView  bfav    = Files.getFileAttributeView(
                                   FileSystems.getDefault().getPath("/dev/null"),
                                   BasicFileAttributeView.class
                                  );
BasicFileAttributes     bfa     = bfav.readAttributes();
System.out.println(bfa.lastAccessTime());
  1. We get the default FileSystem, so that we can use it in the next step.
  2. We get a Path using the FileSystem, so that we can use it in the next step
  3. We get the BasicFileAttributeView (which represents the ability to read a BasicFileAttribute) using the Path, so that ...
  4. We get the BasicFileAttribute using the BasicFileAttributeView, so that ...
  5. We get the lastAccessTime (a FileTime), ...
  6. We print it using FileTime::toString
于 2013-05-04T12:36:14.513 回答