Documentation

The Java™ Tutorials
Hide TOC
File Operations文件操作
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)

File Operations文件操作

The Files class is the other primary entrypoint of the java.nio.file package. Files类是java.nio.file包的另一个主要入口点。This class offers a rich set of static methods for reading, writing, and manipulating files and directories. 此类提供了一组丰富的静态方法,用于读取、写入和操作文件和目录。The Files methods work on instances of Path objects. Files方法处理Path对象的实例。Before proceeding to the remaining sections, you should familiarize yourself with the following common concepts:在继续进行其余部分之前,您应该熟悉以下常见概念:

Releasing System Resources释放系统资源

Many of the resources that are used in this API, such as streams or channels, implement or extend the java.io.Closeable interface. 此API中使用的许多资源(如流或通道)实现或扩展了java.io.Closeable接口。A requirement of a Closeable resource is that the close method must be invoked to release the resource when no longer required. Closeable资源的一个要求是,当不再需要时,必须调用close方法来释放资源。Neglecting to close a resource can have a negative implication on an application's performance. 忽略关闭资源可能会对应用程序的性能产生负面影响。The try-with-resources statement, described in the next section, handles this step for you.下一节将介绍try-with-resources语句,它为您处理此步骤。

Catching Exceptions捕获异常

With file I/O, unexpected conditions are a fact of life: a file exists (or doesn't exist) when expected, the program doesn't have access to the file system, the default file system implementation does not support a particular function, and so on. 对于文件I/O,意外情况是一个事实:文件在预期情况下存在(或不存在),程序无法访问文件系统,默认文件系统实现不支持特定功能,等等。Numerous errors can be encountered.可能会遇到许多错误。

All methods that access the file system can throw an IOException. 所有访问文件系统的方法都可以引发IOExceptionIt is best practice to catch these exceptions by embedding these methods into a try-with-resources statement, introduced in the Java SE 7 release. 捕获这些异常的最佳实践是将这些方法嵌入到JavaSE7版本中引入的try-with-resources语句中。The try-with-resources statement has the advantage that the compiler automatically generates the code to close the resource(s) when no longer required. try-with-resources语句的优点是,编译器会自动生成代码,以便在不再需要时关闭资源。The following code shows how this might look:下面的代码显示了它的外观:

Charset charset = Charset.forName("US-ASCII");
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
}

For more information, see The try-with-resources Statement.有关更多信息,请参阅try-with-resources语句。

Alternatively, you can embed the file I/O methods in a try block and then catch any exceptions in a catch block. 或者,您可以将文件I/O方法嵌入到try块中,然后在catch块中捕获任何异常。If your code has opened any streams or channels, you should close them in a finally block. 如果代码已打开任何流或通道,则应在finally块中关闭它们。The previous example would look something like the following using the try-catch-finally approach:使用try-catch-finally方法,前面的示例类似于以下内容:

Charset charset = Charset.forName("US-ASCII");
String s = ...;
BufferedWriter writer = null;
try {
    writer = Files.newBufferedWriter(file, charset);
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
} finally {
    if (writer != null) writer.close();
}

For more information, see Catching and Handling Exceptions.有关更多信息,请参阅捕获和处理异常

In addition to IOException, many specific exceptions extend FileSystemException. 除了IOException之外,许多特定的异常扩展了FileSystemExceptionThis class has some useful methods that return the file involved (getFile), the detailed message string (getMessage), the reason why the file system operation failed (getReason), and the "other" file involved, if any (getOtherFile).此类具有一些有用的方法,可返回所涉及的文件(getFile)、详细消息字符串(getMessage)、文件系统操作失败的原因(getReason)以及所涉及的“其他”文件(如果有)(getOtherFile)。

The following code snippet shows how the getFile method might be used:以下代码段显示了如何使用getFile方法:

try (...) {
    ...    
} catch (NoSuchFileException x) {
    System.err.format("%s does not exist\n", x.getFile());
}

For purposes of clarity, the file I/O examples in this lesson may not show exception handling, but your code should always include it.为清楚起见,本课程中的文件I/O示例可能未显示异常处理,但您的代码应始终包含异常处理。

Varargs

Several Files methods accept an arbitrary number of arguments when flags are specified. 指定标志时,多个Files方法接受任意数量的参数。For example, in the following method signature, the ellipses notation after the CopyOption argument indicates that the method accepts a variable number of arguments, or varargs, as they are typically called:例如,在以下方法签名中,CopyOption参数后的省略号表示该方法接受可变数量的参数或varargs,因为它们通常被调用:

Path Files.move(Path, Path, CopyOption...)

When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array (CopyOption[]) of values.当一个方法接受varargs参数时,可以向它传递一个逗号分隔的值列表或一个值数组(CopyOption[])。

In the move example, the method can be invoked as follows:move示例中,可以按如下方式调用该方法:

import static java.nio.file.StandardCopyOption.*;

Path source = ...;
Path target = ...;
Files.move(source,
           target,
           REPLACE_EXISTING,
           ATOMIC_MOVE);

For more information about varargs syntax, see Arbitrary Number of Arguments.有关varargs语法的详细信息,请参阅任意数量的参数

Atomic Operations原子操作

Several Files methods, such as move, can perform certain operations atomically in some file systems.一些Files方法(如move)可以在某些文件系统中以原子方式执行某些操作。

An atomic file operation is an operation that cannot be interrupted or "partially" performed. 原子文件操作是一种不能被中断或“部分”执行的操作。Either the entire operation is performed or the operation fails. 要么执行整个操作,要么操作失败。This is important when you have multiple processes operating on the same area of the file system, and you need to guarantee that each process accesses a complete file.当多个进程在文件系统的同一区域上运行时,这一点很重要,并且需要确保每个进程访问一个完整的文件。

Method Chaining方法链

Many of the file I/O methods support the concept of method chaining.许多文件I/O方法都支持方法链接的概念。

You first invoke a method that returns an object. 首先调用一个返回对象的方法。You then immediately invoke a method on that object, which returns yet another object, and so on. 然后立即调用该对象上的方法,该方法返回另一个对象,依此类推。Many of the I/O examples use the following technique:许多I/O示例使用以下技术:

String value = Charset.defaultCharset().decode(buf).toString();
UserPrincipal group =
    file.getFileSystem().getUserPrincipalLookupService().
         lookupPrincipalByName("me");

This technique produces compact code and enables you to avoid declaring temporary variables that you don't need.这种技术生成紧凑的代码,并使您能够避免声明不需要的临时变量。

What Is a Glob?什么是Glob?

Two methods in the Files class accept a glob argument, but what is a glob?Files类中的两个方法接受glob参数,但什么是glob

You can use glob syntax to specify pattern-matching behavior.可以使用glob语法指定模式匹配行为。

A glob pattern is specified as a string and is matched against other strings, such as directory or file names. glob模式被指定为字符串,并与其他字符串(如目录或文件名)匹配。Glob syntax follows several simple rules:Glob语法遵循几个简单规则:

Here are some examples of glob syntax:以下是glob语法的一些示例:


Note: If you are typing the glob pattern at the keyboard and it contains one of the special characters, you must put the pattern in quotes ("*"), use the backslash (\*), or use whatever escape mechanism is supported at the command line. 如果在键盘上键入glob模式,并且该模式包含一个特殊字符,则必须将该模式置于引号("*")中,使用反斜杠(\*),或使用命令行支持的任何转义机制。

The glob syntax is powerful and easy to use. glob语法功能强大且易于使用。However, if it is not sufficient for your needs, you can also use a regular expression. 但是,如果它不足以满足您的需要,您也可以使用正则表达式。For more information, see the Regular Expressions lesson.有关详细信息,请参阅正则表达式课程

For more information about the glob syntax, see the API specification for the getPathMatcher method in the FileSystem class.有关glob语法的更多信息,请参阅FileSystem类中getPathMatcher方法的API规范。

Link Awareness链接意识

The Files class is "link aware." Files类是“链接感知的”。Every Files method either detects what to do when a symbolic link is encountered, or it provides an option enabling you to configure the behavior when a symbolic link is encountered.每个Files方法要么检测遇到符号链接时要执行的操作,要么提供一个选项,使您能够配置遇到符号链接时的行为。


Previous page: Path Operations
Next page: Checking a File or Directory