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 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:在继续进行其余部分之前,您应该熟悉以下常见概念:
Many of the resources that are used in this API, such as streams or channels, implement or extend the 此API中使用的许多资源(如流或通道)实现或扩展了java.io.Closeable
interface. 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语句,它为您处理此步骤。
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
. IOException
。It is best practice to catch these exceptions by embedding these methods into a 捕获这些异常的最佳实践是将这些方法嵌入到JavaSE7版本中引入的try-
with-resources statement, introduced in the Java SE 7 release. 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 或者,您可以将文件I/O方法嵌入到try
block and then catch any exceptions in a catch
block. 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
之外,许多特定的异常扩展了FileSystemException
。This 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示例可能未显示异常处理,但您的代码应始终包含异常处理。
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 (当一个方法接受varargs参数时,可以向它传递一个逗号分隔的值列表或一个值数组(CopyOption[]
) of values.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语法的详细信息,请参阅任意数量的参数。
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.当多个进程在文件系统的同一区域上运行时,这一点很重要,并且需要确保每个进程访问一个完整的文件。
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.这种技术生成紧凑的代码,并使您能够避免声明不需要的临时变量。
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语法遵循几个简单规则:
*
, matches any number of characters (including none).*
,匹配任意数量的字符(包括无字符)。**
, works like *
but crosses directory boundaries. **
与*
类似,但跨越了目录边界。?
, matches exactly one character.?
正好匹配一个字符。{sun,moon,stars}
{temp*,tmp*}
-
) is used, a range of characters. For example:-
)时表示一系列字符。例如:
[aeiou]
[0-9]
[A-Z]
[a-z,A-Z]
*
, ?
, and \
match themselves.*
、?
和\
匹配它们自己。*
, ?
, or the other special characters, you can escape them by using the backslash character, \
. *
、?
或其他特殊字符,可以使用反斜杠字符\
对其进行转义。\\
matches a single backslash, and \?
matches the question mark.\\
匹配一个反斜杠,而\?
匹配问号。Here are some examples of glob syntax:以下是glob语法的一些示例:
*.html
– ???
– *[0-9]*
– *.{htm,html,pdf}
– a?*.java
– a
, followed by at least one letter or digit, and ending with .javaa
开头、后跟至少一个字母或数字、以.java结尾的任何字符串{foo*,*[0-9]*}
– "*"
), use the backslash (\*
), or use whatever escape mechanism is supported at the command line. "*"
)中,使用反斜杠(\*
),或使用命令行支持的任何转义机制。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 有关glob语法的更多信息,请参阅getPathMatcher
method in the FileSystem
class.FileSystem
类中getPathMatcher
方法的API规范。
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
方法要么检测遇到符号链接时要执行的操作,要么提供一个选项,使您能够配置遇到符号链接时的行为。