The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The definition of metadata is "data about other data." 元数据的定义是“关于其他数据的数据”。With a file system, the data is contained in its files and directories, and the metadata tracks information about each of these objects: Is it a regular file, a directory, or a link? 对于文件系统,数据包含在其文件和目录中,元数据跟踪关于每个对象的信息:是常规文件、目录还是链接?What is its size, creation date, last modified date, file owner, group owner, and access permissions?它的大小、创建日期、上次修改日期、文件所有者、组所有者和访问权限是多少?
A file system's metadata is typically referred to as its file attributes. 文件系统的元数据通常称为其文件属性。The Files
class includes methods that can be used to obtain a single attribute of a file, or to set an attribute.Files
类包括可用于获取文件的单个属性或设置属性的方法。
size(Path) |
|
isDirectory(Path, LinkOption) |
Path locates a file that is a directory.Path 找到的文件是目录,则返回true 。 |
isRegularFile(Path, LinkOption...) |
Path locates a file that is a regular file.Path 找到的文件是常规文件,则返回true 。 |
isSymbolicLink(Path) |
Path locates a file that is a symbolic link.Path 找到的文件是符号链接,则返回true 。 |
isHidden(Path) |
Path locates a file that is considered hidden by the file system.Path 找到被文件系统视为隐藏的文件,则返回true 。 |
getLastModifiedTime(Path, LinkOption...) setLastModifiedTime(Path, FileTime) |
|
getOwner(Path, LinkOption...) setOwner(Path, UserPrincipal) |
|
getPosixFilePermissions(Path, LinkOption...) setPosixFilePermissions(Path, Set<PosixFilePermission>) |
|
getAttribute(Path, String, LinkOption...) setAttribute(Path, String, Object, LinkOption...) |
If a program needs multiple file attributes around the same time, it can be inefficient to use methods that retrieve a single attribute. 如果一个程序几乎同时需要多个文件属性,那么使用检索单个属性的方法可能效率低下。Repeatedly accessing the file system to retrieve a single attribute can adversely affect performance. 重复访问文件系统以检索单个属性可能会对性能产生不利影响。For this reason, the 因此,Files
class provides two readAttributes
methods to fetch a file's attributes in one bulk operation.Files
类提供了两个readAttributes
方法,用于在一次批量操作中获取文件的属性。
readAttributes(Path, String, LinkOption...) |
String parameter identifies the attributes to be read.String 参数标识要读取的属性。 |
readAttributes(Path, Class<A>, LinkOption...) |
Class<A> parameter is the type of attributes requested and the method returns an object of that class.Class<A> 参数是请求的属性类型,该方法返回该类的对象。 |
Before showing examples of the readAttributes
methods, it should be mentioned that different file systems have different notions about which attributes should be tracked. For this reason, related file attributes are grouped together into views. A view maps to a particular file system implementation, such as POSIX or DOS, or to a common functionality, such as file ownership.
The supported views are as follows:支持的视图如下所示:
BasicFileAttributeView
– Provides a view of basic attributes that are required to be supported by all file system implementations.DosFileAttributeView
– Extends the basic attribute view with the standard four bits supported on file systems that support the DOS attributes.PosixFileAttributeView
– Extends the basic attribute view with attributes supported on file systems that support the POSIX family of standards, such as UNIX. These attributes include file owner, group owner, and the nine related access permissions.FileOwnerAttributeView
– Supported by any file system implementation that supports the concept of a file owner.AclFileAttributeView
– Supports reading or updating a file's Access Control Lists (ACL). The NFSv4 ACL model is supported. Any ACL model, such as the Windows ACL model, that has a well-defined mapping to the NFSv4 model might also be supported.UserDefinedFileAttributeView
– Enables support of metadata that is user defined. This view can be mapped to any extension mechanisms that a system supports. In the Solaris OS, for example, you can use this view to store the MIME type of a file.A specific file system implementation might support only the basic file attribute view, or it may support several of these file attribute views. A file system implementation might support other attribute views not included in this API.
In most instances, you should not have to deal directly with any of the FileAttributeView
interfaces. (If you do need to work directly with the FileAttributeView
, you can access it via the getFileAttributeView(Path, Class<V>, LinkOption...)
method.)
The readAttributes
methods use generics and can be used to read the attributes for any of the file attributes views. The examples in the rest of this page use the readAttributes
methods.
The remainder of this section covers the following topics:本节剩余部分将介绍以下主题:
As mentioned previously, to read the basic attributes of a file, you can use one of the Files.readAttributes
methods, which reads all the basic attributes in one bulk operation. This is far more efficient than accessing the file system separately to read each individual attribute. The varargs argument currently supports the LinkOption
enum, NOFOLLOW_LINKS
. Use this option when you do not want symbolic links to be followed.如果不希望跟随符号链接,请使用此选项。
creationTime
, lastModifiedTime
, and lastAccessTime
. Any of these time stamps might not be supported in a particular implementation, in which case the corresponding accessor method returns an implementation-specific value. When supported, the time stamp is returned as an FileTime
object. The following code snippet reads and prints the basic file attributes for a given file and uses the methods in the 下面的代码段读取并打印给定文件的基本文件属性,并使用BasicFileAttributes
class.BasicFileAttributes
类中的方法。
Path file = ...; BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); System.out.println("creationTime: " + attr.creationTime()); System.out.println("lastAccessTime: " + attr.lastAccessTime()); System.out.println("lastModifiedTime: " + attr.lastModifiedTime()); System.out.println("isDirectory: " + attr.isDirectory()); System.out.println("isOther: " + attr.isOther()); System.out.println("isRegularFile: " + attr.isRegularFile()); System.out.println("isSymbolicLink: " + attr.isSymbolicLink()); System.out.println("size: " + attr.size());
In addition to the accessor methods shown in this example, there is a fileKey
method that returns either an object that uniquely identifies the file or null
if no file key is available.
The following code snippet sets the last modified time in milliseconds:
Path file = ...; BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); long currentTime = System.currentTimeMillis(); FileTime ft = FileTime.fromMillis(currentTime); Files.setLastModifiedTime(file, ft); }
DOS file attributes are also supported on file systems other than DOS, such as Samba. DOS文件属性在DOS以外的文件系统(如Samba)上也受支持。The following snippet uses the methods of the 以下代码段使用DosFileAttributes
class.DosFileAttributes
类的方法。
Path file = ...; try { DosFileAttributes attr = Files.readAttributes(file, DosFileAttributes.class); System.out.println("isReadOnly is " + attr.isReadOnly()); System.out.println("isHidden is " + attr.isHidden()); System.out.println("isArchive is " + attr.isArchive()); System.out.println("isSystem is " + attr.isSystem()); } catch (UnsupportedOperationException x) { System.err.println("DOS file" + " attributes not supported:" + x); }
However, you can set a DOS attribute using the setAttribute(Path, String, Object, LinkOption...)
method, as follows:
Path file = ...; Files.setAttribute(file, "dos:hidden", true);
POSIX is an acronym for Portable Operating System Interface for UNIX and is a set of IEEE and ISO standards designed to ensure interoperability among different flavors of UNIX. POSIX是UNIX便携式操作系统接口的首字母缩写,是一组IEEE和ISO标准,旨在确保不同风格UNIX之间的互操作性。If a program conforms to these POSIX standards, it should be easily ported to other POSIX-compliant operating systems.如果一个程序符合这些POSIX标准,它应该很容易移植到其他符合POSIX标准的操作系统。
Besides file owner and group owner, POSIX supports nine file permissions: read, write, and execute permissions for the file owner, members of the same group, and "everyone else."除了文件所有者和组所有者之外,POSIX还支持九种文件权限:文件所有者、同一组成员和“其他所有人”的读、写和执行权限。
The following code snippet reads the POSIX file attributes for a given file and prints them to standard output. 下面的代码片段读取给定文件的POSIX文件属性,并将其打印到标准输出。The code uses the methods in the 代码使用PosixFileAttributes
class.PosixFileAttributes
类中的方法。
Path file = ...; PosixFileAttributes attr = Files.readAttributes(file, PosixFileAttributes.class); System.out.format("%s %s %s%n", attr.owner().getName(), attr.group().getName(), PosixFilePermissions.toString(attr.permissions()));
The PosixFilePermissions
helper class provides several useful methods, as follows:PosixFilePermissions
助手类提供了几种有用的方法,如下所示:
toString
method, used in the previous code snippet, converts the file permissions to a string (for example, rw-r--r--
).fromString
method accepts a string representing the file permissions and constructs a Set
of file permissions.asFileAttribute
method accepts a Set
of file permissions and constructs a file attribute that can be passed to the Path.createFile
or Path.createDirectory
method.The following code snippet reads the attributes from one file and creates a new file, assigning the attributes from the original file to the new file:以下代码段从一个文件中读取属性并创建一个新文件,将原始文件中的属性指定给新文件:
Path sourceFile = ...; Path newFile = ...; PosixFileAttributes attrs = Files.readAttributes(sourceFile, PosixFileAttributes.class); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(attrs.permissions()); Files.createFile(file, attr);
The asFileAttribute
method wraps the permissions as a FileAttribute
. asFileAttribute
方法将权限包装为FileAttribute
。The code then attempts to create a new file with those permissions. 然后,代码尝试创建具有这些权限的新文件。Note that the 请注意,umask
also applies, so the new file might be more secure than the permissions that were requested.umask
也适用,因此新文件可能比请求的权限更安全。
To set a file's permissions to values represented as a hard-coded string, you can use the following code:要将文件权限设置为表示为硬编码字符串的值,可以使用以下代码:
Path file = ...; Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); Files.setPosixFilePermissions(file, perms);
The
example recursively changes the permissions of files in a manner similar to the Chmod
chmod
utility.
To translate a name into an object you can store as a file owner or a group owner, you can use the UserPrincipalLookupService
service. This service looks up a name or group name as a string and returns a UserPrincipal
object representing that string. You can obtain the user principal look-up service for the default file system by using the FileSystem.getUserPrincipalLookupService
method.
The following code snippet shows how to set the file owner by using the 以下代码段显示了如何使用setOwner
method:setOwner
方法设置文件所有者:
Path file = ...; UserPrincipal owner = file.GetFileSystem().getUserPrincipalLookupService() .lookupPrincipalByName("sally"); Files.setOwner(file, owner);
There is no special-purpose method in the Files
class for setting a group owner. Files
类中没有用于设置组所有者的专用方法。However, a safe way to do so directly is through the POSIX file attribute view, as follows:但是,直接执行此操作的安全方法是通过POSIX文件属性视图,如下所示:
Path file = ...; GroupPrincipal group = file.getFileSystem().getUserPrincipalLookupService() .lookupPrincipalByGroupName("green"); Files.getFileAttributeView(file, PosixFileAttributeView.class) .setGroup(group);
User-Defined File Attributes
If the file attributes supported by your file system implementation aren't sufficient for your needs, you can use the 如果文件系统实现支持的文件属性不足以满足您的需要,则可以使用UserDefinedAttributeView
to create and track your own file attributes.UserDefinedAttributeView
创建和跟踪您自己的文件属性。
Some implementations map this concept to features like NTFS Alternative Data Streams and extended attributes on file systems such as ext3 and ZFS. 一些实现将此概念映射到诸如NTFS替代数据流和文件系统(如ext3和ZFS)上的扩展属性等功能。Most implementations impose restrictions on the size of the value, for example, ext3 limits the size to 4 kilobytes.大多数实现对值的大小施加限制,例如,ext3将值的大小限制为4KB。
A file's MIME type can be stored as a user-defined attribute by using this code snippet:通过使用以下代码段,可以将文件的MIME类型存储为用户定义的属性:
Path file = ...; UserDefinedFileAttributeView view = Files .getFileAttributeView(file, UserDefinedFileAttributeView.class); view.write("user.mimetype", Charset.defaultCharset().encode("text/html");
To read the MIME type attribute, you would use this code snippet:要读取MIME类型属性,请使用以下代码段:
Path file = ...; UserDefinedFileAttributeView view = Files .getFileAttributeView(file,UserDefinedFileAttributeView.class); String name = "user.mimetype"; ByteBuffer buf = ByteBuffer.allocate(view.size(name)); view.read(name, buf); buf.flip(); String value = Charset.defaultCharset().decode(buf).toString();
The
example shows how to get, set, and delete a user-defined attribute.Xdd
示例演示如何获取、设置和删除用户定义的属性。Xdd
UnsupportedOperationException
when trying to access the user-defined attribute view, you need to remount the file system. UnsupportedOperationException
,则需要重新装载文件系统。$ sudo mount -o remount,user_xattr /
If you want to make the change permanent, add an entry to 如果要使更改永久化,请在/etc/fstab
./etc/fstab
中添加一个条目。
You can use the 您可以使用FileStore
class to learn information about a file store, such as how much space is available. FileStore
类来了解有关文件存储的信息,例如可用空间大小。The getFileStore(Path)
method fetches the file store for the specified file.getFileStore(Path)
方法获取指定文件的文件存储。
The following code snippet prints the space usage for the file store where a particular file resides:以下代码段打印特定文件所在的文件存储的空间使用情况:
Path file = ...; FileStore store = Files.getFileStore(file); long total = store.getTotalSpace() / 1024; long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024; long avail = store.getUsableSpace() / 1024;
The DiskUsage
example uses this API to print disk space information for all the stores in the default file system. DiskUsage
示例使用此API打印默认文件系统中所有存储的磁盘空间信息。This example uses the 本例使用getFileStores
method in the FileSystem
class to fetch all the file stores for the file system.FileSystem
类中的getFileStores
方法获取文件系统的所有文件存储。