epubjs
Version:
Render ePub documents in the browser, across many devices
290 lines (281 loc) • 53.8 kB
HTML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>The NIO File API</title><link rel="stylesheet" href="core.css" type="text/css"/><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"/></head><body><div class="sect1" title="The NIO File API"><div class="titlepage"><div><div><h1 class="title"><a id="I_sect112_id757753"/>The NIO File API</h1></div></div></div><p>We are now going to turn our attention from the original, “classic”
Java File API to the new, NIO, File API introduced with Java 7. As we
mentioned earlier, the NIO File API can be thought of as either a
replacement for or a complement to the classic API. Included in the NIO
package, the new API is nominally part of an effort to move Java toward a
higher performance and more flexible style of I/O supporting
<span class="emphasis"><em>selectable</em></span> and asynchronously interruptable
<span class="emphasis"><em>channels</em></span>. However, in the context of working with
files, the new API’s strength is that it provides a fuller abstraction of
the <span class="emphasis"><em>filesystem</em></span> in Java.</p><p>In addition to better support for existing, real world, filesystem
types—including for the first time the ability to copy and move files,
manage links, and get detailed file attributes like owners and
permissions—the new File API allows entirely new types of filesystems to
be implemented directly in Java. The best example of this is the new ZIP
filesystem provider that makes it possible to “mount” a ZIP archive file
as a filesystem and work with the files within it directly using the
standard APIs, just like any other filesystem. Additionally, the NIO File
package provides some utilities that would have saved Java developers a
lot of repeated code over the years, including directory tree change
monitoring, filesystem traversal (a visitor pattern), filename “globbing,”
and convenience methods to read entire files directly into memory.</p><p>We’ll cover the basic File API in this section and return to the NIO
API again at the end of the chapter when we cover the full details of NIO
buffers and channels. In particular, we’ll talk about <code class="literal">ByteChannel</code>s and <code class="literal">FileChannel</code>, which you can think of as
alternate, buffer-oriented streams for reading and writing files and other
types of data.</p><div class="sect2" title="FileSystem and Path"><div class="titlepage"><div><div><h2 class="title"><a id="id1735670"/>FileSystem and Path</h2></div></div></div><p><a id="idx10703" class="indexterm"/> <a id="idx10711" class="indexterm"/> <a id="idx10729" class="indexterm"/> <a id="idx10742" class="indexterm"/>The main players in the <a id="I_indexterm12_id757867" class="indexterm"/><code class="literal">java.nio.file</code> package
are: the <code class="literal">FileSystem</code>, which represents
an underlying storage mechanism and serves as a factory for <code class="literal">Path</code> objects; the <code class="literal">Path</code>, which represents a file or directory
within the filesystem; and the <code class="literal">Files</code>
utility, which contains a rich set of static methods for manipulating
<code class="literal">Path</code> objects to perform all of the
basic file operations analogous to the classic API.</p><p>The <a id="I_indexterm12_id757909" class="indexterm"/><code class="literal">FileSystems</code> (plural)
class is our starting point. It is a factory for a <code class="literal">FileSystem</code> object:</p><a id="I_programlisting12_id757926"/><pre class="programlisting"><code class="c1">// The default host computer filesystem</code>
<code class="n">FileSystem</code> <code class="n">fs</code> <code class="o">=</code> <code class="n">FileSystems</code><code class="o">.</code><code class="na">getDefault</code><code class="o">();</code>
<code class="c1">// A custom filesystem</code>
<code class="n">URI</code> <code class="n">zipURI</code> <code class="o">=</code> <code class="n">URI</code><code class="o">.</code><code class="na">create</code><code class="o">(</code><code class="s">"jar:file:/Users/pat/tmp/MyArchive.zip"</code><code class="o">);</code>
<code class="n">FileSystem</code> <code class="n">zipfs</code> <code class="o">=</code> <code class="n">FileSystems</code><code class="o">.</code><code class="na">newFileSystem</code><code class="o">(</code> <code class="n">zipURI</code><code class="o">,</code> <code class="n">env</code> <code class="o">)</code> <code class="o">);</code></pre><p>As shown in this snippet, often we’ll simply ask for the default
filesystem to manipulate files in the host computer’s environment, as
with the classic API. But the <code class="literal">FileSystems</code> class can also construct a
<code class="literal">FileSystem</code> by taking a URI (a special
identifier) that references a custom filesystem type. We’ll show an
example of working with the ZIP filesystem provider later in this
chapter when we discuss data compression.</p><p><code class="literal">FileSystem</code> implements <code class="literal">Closeable</code> and when a <code class="literal">FileSystem</code> is closed, all open file channels
and other streaming objects associated with it are closed as well.
Attempting to read or write to those channels will throw an exception at
that point. Note that the default filesystem (associated with the host
computer) cannot be closed.</p><p>Once we have a <code class="literal">FileSystem</code>, we
can use it as a factory for <code class="literal">Path</code>
objects that represent files or directories. A <code class="literal">Path</code> can be constructed using a string
representation just like the classic <code class="literal">File</code>, and subsequently used with methods of
the <code class="literal">Files</code> utility to create, read,
write, or delete the item.</p><a id="I_programlisting12_id758004"/><pre class="programlisting"><code class="n">Path</code> <code class="n">fooPath</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/tmp/foo.txt"</code> <code class="o">);</code>
<code class="n">OutputStream</code> <code class="n">out</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">newOutputStream</code><code class="o">(</code> <code class="n">fooPath</code> <code class="o">);</code></pre><p>This example opens an <code class="literal">OutputStream</code> to write to the file <em class="filename">foo.txt</em>. By default, if the file does not
exist, it will be created and if it does exist, it will be truncated
(set to zero length) before new data is written—but you can change these
results using options. We’ll talk more about <code class="literal">Files</code> methods in the next section.</p><p>The <code class="literal">Path</code> object implements the
<code class="literal">java.lang.Iterable</code> interface, which
can be used to iterate through its literal path components (e.g., the
slash separated “tmp” and “foo.txt” in the preceding snippet). Although
if you want to traverse the path to find other files or directories, you
might be more interested in the <code class="literal">DirectoryStream</code> and <code class="literal">FileVisitor</code> that we’ll discuss later. <code class="literal">Path</code> also implements the <a id="I_indexterm12_id758069" class="indexterm"/><code class="literal">java.nio.file.Watchable</code>
interface, which allows it to be monitored for changes. We’ll also
discuss watching file trees for changes in an upcoming section.</p><p>Path has convenience methods for resolving paths relative to a
file or directory.</p><a id="I_programlisting12_id758086"/><pre class="programlisting"><code class="n">Path</code> <code class="n">patPath</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/User/pat/"</code> <code class="o">);</code>
<code class="n">Path</code> <code class="n">patTmp</code> <code class="o">=</code> <code class="n">patPath</code><code class="o">.</code><code class="na">resolve</code><code class="o">(</code><code class="s">"tmp"</code> <code class="o">);</code> <code class="c1">// "/User/pat/tmp"</code>
<code class="c1">// Same as above, using a Path</code>
<code class="n">Path</code> <code class="n">tmpPath</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"tmp"</code> <code class="o">);</code>
<code class="n">Path</code> <code class="n">patTmp</code> <code class="o">=</code> <code class="n">patPath</code><code class="o">.</code><code class="na">resolve</code><code class="o">(</code> <code class="n">tmpPath</code> <code class="o">);</code> <code class="c1">// "/User/pat/tmp"</code>
<code class="c1">// Resolving a given absolute path against any path just yields given path</code>
<code class="n">Path</code> <code class="n">absPath</code> <code class="o">=</code> <code class="n">patPath</code><code class="o">.</code><code class="na">resolve</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">);</code> <code class="c1">// "/tmp"</code>
<code class="c1">// Resolve sibling to Pat (same parent)</code>
<code class="n">Path</code> <code class="n">danPath</code> <code class="o">=</code> <code class="n">patPath</code><code class="o">.</code><code class="na">resolveSibling</code><code class="o">(</code> <code class="s">"dan"</code> <code class="o">);</code> <code class="c1">// "/Users/dan"</code></pre><p>In this snippet, we’ve shown the <code class="literal">Path</code><a id="I_indexterm12_id758103" class="indexterm"/><code class="literal">resolve()</code> and
<a id="I_indexterm12_id758113" class="indexterm"/><code class="literal">resolveSibling()</code>
methods used to find files or directories relative to a given <code class="literal">Path</code> object. The <code class="literal">resolve()</code> method is generally used to append a
relative path to an existing <code class="literal">Path</code>
representing a directory. If the argument provided to the <code class="literal">resolve()</code> method is an absolute path, it will
just yield the absolute path (it acts kind of like the Unix or DOS “cd”
command). The <code class="literal">resolveSibling()</code> method
works the same way, but it is relative to the parent of the target
<code class="literal">Path</code>; this method is useful for
describing the target of a <code class="literal">move()</code>
operation.</p><div class="sect3" title="Path to classic file and back"><div class="titlepage"><div><div><h3 class="title"><a id="id1647957"/>Path to classic file and back</h3></div></div></div><p>To bridge the old and new APIs, corresponding <a id="I_indexterm12_id758173" class="indexterm"/><code class="literal">toPath()</code> and
<a id="I_indexterm12_id758184" class="indexterm"/><code class="literal">toFile()</code> methods have
been provided in <code class="literal">java.io.File</code> and
<code class="literal">java.nio.file.Path</code>, respectively,
to convert to the other form. Of course, the only types of <code class="literal">Path</code>s that can be produced from File are
paths representing files and directories in the default host
filesystem.<a id="I_indexterm12_id758212" class="indexterm"/><a id="I_indexterm12_id758220" class="indexterm"/><a id="I_indexterm12_id758227" class="indexterm"/><a id="I_indexterm12_id758234" class="indexterm"/></p><a id="I_programlisting12_id758241"/><pre class="programlisting"><code class="n">Path</code> <code class="n">tmpPath</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">);</code>
<code class="n">File</code> <code class="n">file</code> <code class="o">=</code> <code class="n">tmpPath</code><code class="o">.</code><code class="na">toFile</code><code class="o">();</code>
<code class="n">File</code> <code class="n">tmpFile</code> <code class="o">=</code> <code class="k">new</code> <code class="n">File</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">);</code>
<code class="n">Path</code> <code class="n">path</code> <code class="o">=</code> <code class="n">tmpFile</code><code class="o">.</code><code class="na">toPath</code><code class="o">();</code></pre></div></div><div class="sect2" title="NIO File Operations"><div class="titlepage"><div><div><h2 class="title"><a id="id1735672"/>NIO File Operations</h2></div></div></div><p><a id="idx10712" class="indexterm"/> <a id="idx10730" class="indexterm"/>Once we have a <code class="literal">Path</code>, we
can operate on it with static methods of the <code class="literal">Files</code> utility to create the path as a file or
directory, read and write to it, and interrogate and set its properties.
We’ll list the bulk of them and then discuss some of the more important
ones as we proceed.</p><p>The following table summarizes these methods of the <code class="literal">java.nio.file.Files</code> class. As you might
expect, because the <code class="literal">Files</code> class
handles all types of file operations, it contains a large number of
methods. To make the table more readable, we have elided overloaded
forms of the same method (those taking different kinds of arguments) and
grouped corresponding and related types of methods together.<a id="I_indexterm12_id758312" class="indexterm"/><a id="I_indexterm12_id758317" class="indexterm"/><a id="I_indexterm12_id758323" class="indexterm"/><a id="I_indexterm12_id758328" class="indexterm"/><a id="I_indexterm12_id758334" class="indexterm"/><a id="I_indexterm12_id758339" class="indexterm"/><a id="I_indexterm12_id758345" class="indexterm"/><a id="I_indexterm12_id758350" class="indexterm"/><a id="I_indexterm12_id758356" class="indexterm"/><a id="I_indexterm12_id758361" class="indexterm"/><a id="I_indexterm12_id758366" class="indexterm"/><a id="I_indexterm12_id758372" class="indexterm"/><a id="I_indexterm12_id758377" class="indexterm"/><a id="I_indexterm12_id758383" class="indexterm"/><a id="I_indexterm12_id758388" class="indexterm"/><a id="I_indexterm12_id758394" class="indexterm"/><a id="I_indexterm12_id758399" class="indexterm"/><a id="I_indexterm12_id758405" class="indexterm"/><a id="I_indexterm12_id758410" class="indexterm"/><a id="I_indexterm12_id758416" class="indexterm"/><a id="I_indexterm12_id758421" class="indexterm"/><a id="I_indexterm12_id758427" class="indexterm"/><a id="I_indexterm12_id758432" class="indexterm"/><a id="I_indexterm12_id758438" class="indexterm"/><a id="I_indexterm12_id758443" class="indexterm"/><a id="I_indexterm12_id758449" class="indexterm"/><a id="I_indexterm12_id758454" class="indexterm"/><a id="I_indexterm12_id758459" class="indexterm"/><a id="I_indexterm12_id758465" class="indexterm"/><a id="I_indexterm12_id758470" class="indexterm"/><a id="I_indexterm12_id758476" class="indexterm"/><a id="I_indexterm12_id758482" class="indexterm"/><a id="I_indexterm12_id758487" class="indexterm"/><a id="I_indexterm12_id758493" class="indexterm"/><a id="I_indexterm12_id758498" class="indexterm"/><a id="I_indexterm12_id758504" class="indexterm"/><a id="I_indexterm12_id758509" class="indexterm"/><a id="I_indexterm12_id758515" class="indexterm"/><a id="I_indexterm12_id758520" class="indexterm"/><a id="I_indexterm12_id758526" class="indexterm"/><a id="I_indexterm12_id758531" class="indexterm"/><a id="I_indexterm12_id758537" class="indexterm"/><a id="I_indexterm12_id758542" class="indexterm"/><a id="I_indexterm12_id758550" class="indexterm"/><a id="I_indexterm12_id758555" class="indexterm"/></p><div class="table"><a id="id2170506"/><p class="title">Table 12-2. NIO Files methods</p><div class="table-contents"><table summary="NIO Files methods" style="border: none;"><colgroup><col/><col/><col/></colgroup><thead><tr><th style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Method</th><th style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Return type</th><th style="border-bottom: 0.5pt solid ; ">Description</th></tr></thead><tbody><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">copy()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">long or <code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Copy a stream to a file path, file path to stream, or
path to path. Returns the number of bytes copied or the target
<code class="literal">Path</code>. A target file may
optionally be replaced if it exists (the default is to fail if
the target exists). Copying a directory results in an empty
directory at the target (the contents are not copied). Copying a
symbolic link copies the linked files data (producing a regular
file copy).</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">createDirectory()</code>,
<code class="literal">createDirectories()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Create a single directory or all directories in a
specified path. <code class="literal">createDirectory()</code> throws an exception
if the directory already exists, whereas <code class="literal">createDirectories()</code> will ignore
existing directories and only create as needed.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">createFile()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Creates an empty file. The operation is atomic and will
only succeed if the file does not exist. (This property can be
used to create flag files to guard resources, etc.)</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">createTempDirectory()</code>,
<code class="literal">createTempFile()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Create a temporary, guaranteed, uniquely named directory
or file with the specified prefix. Optionally place it in the
system default temp directory.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">delete()</code>, <code class="literal">deleteIfExists()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">void</td><td style="border-bottom: 0.5pt solid ; ">Delete a file or an empty directory. <code class="literal">delete</code><code class="literal">IfExists()</code> will
not throw an exception if the file does not exist.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">exists()</code>, <code class="literal">notExists()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">boolean</td><td style="border-bottom: 0.5pt solid ; ">Determine whether the file exists (<code class="literal">notExists()</code> simply returns the
opposite). Optionally specify whether links should be followed
(by default they are).</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">exists()</code>, <code class="literal">isDirectory()</code>, <code class="literal">isExecutable()</code>, <code class="literal">isHidden()</code>, <code class="literal">isReadable()</code>, <code class="literal">isRegularFile()</code>, <code class="literal">isWriteable()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">boolean</td><td style="border-bottom: 0.5pt solid ; ">Tests basic file features: whether the path exists, is a
directory, and other basic attributes.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">createLink()</code>, <code class="literal">createSymbolicLink()</code>, <code class="literal">isSymbolicLink()</code>, <code class="literal">readSymbolicLink()</code>, <code class="literal">createLink()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">boolean or <code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Create a hard or symbolic link, test to see if a file is
a symbolic link, or read the target file pointed to by the
symbolic link. Symbolic links are files that reference other
files. Regular (“hard”) links are low-level mirrors of a file
where two filenames point to the same underlying data. If you
don’t know which to use, use a symbolic link.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">getAttribute()</code>,
<code class="literal">setAttribute()</code>, <code class="literal">getFileAttributeView()</code>, <code class="literal">readAttributes()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Object</code>, <code class="literal">Map</code>, or <code class="literal">FileAttributeView</code></td><td style="border-bottom: 0.5pt solid ; ">Get or set filesystem-specific file attributes such as
access and update times, detailed permissions, and owner
information using implementation-specific names.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">getFileStore()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">FileStore</code></td><td style="border-bottom: 0.5pt solid ; ">Get a <code class="literal">FileStore</code> object
that represents the device, volume, or other type of partition
of the filesystem on which the path resides.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">getLastModifiedTime()</code>,
<code class="literal">setLastModifiedTime()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">FileTime</code> or <code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Get or set the last modified time of a file or
directory.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">getOwner()</code>, <code class="literal">setOwner()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">UserPrincipal</code></td><td style="border-bottom: 0.5pt solid ; ">Get or set a <code class="literal">UserPrincipal</code> object representing the
owner of the file. Use <code class="literal">toString()</code> or <code class="literal">getName()</code> to get a string
representation of the user name.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">getPosixFilePermissions()</code>, <code class="literal">setPosixFilePermissions()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Set</code> or <code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Get or set the full POSIX user-group-other style read and
write permissions for the path as a Set of <code class="literal">PosixFilePermission</code> enum
values.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">isSameFile()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">boolean</td><td style="border-bottom: 0.5pt solid ; ">Test to see whether the two paths reference the same file
(which may potentially be true even if the paths are not
identical).</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">move()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Move a file or directory by renaming or copying it,
optionally specifying whether to replace any existing target.
Rename will be used unless a copy is required to move a file
across file stores or filesystems. Directories can be moved
using this method only if the simple rename is possible or if
the directory is empty. If a directory move requires copying
files across file stores or filesystems, the method throws an
<code class="literal">IOException</code>. (In this case,
you must copy the files yourself. See <code class="literal">walkFileTree()</code>.)</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">newBufferedReader()</code>,
<code class="literal">newBufferedWriter()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">BufferedReader</code> or
<code class="literal">BufferedWriter</code></td><td style="border-bottom: 0.5pt solid ; ">Open a file for reading via a <code class="literal">BufferedReader</code>, or create and open a
file for writing via a <code class="literal">BufferedWriter</code>. In both cases, a
character encoding is specified.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">newByteChannel()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">SeekableByteChannel</code></td><td style="border-bottom: 0.5pt solid ; ">Create a new file or open an existing file as a seekable
byte channel. (See the full discussion of NIO later in this
chapter.) Consider using <code class="literal">FileChannel</code><code class="literal">open()</code> as an alternative.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">newDirectoryStream()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">DirectoryStream</code></td><td style="border-bottom: 0.5pt solid ; ">Return a <code class="literal">DirectoryStream</code> for iterating over a
directory hierarchy. Optionally, supply a glob pattern or filter
object to match files.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">newInputStream()</code>,
<code class="literal">newOutputStream()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">InputStream</code> or
<code class="literal">OutputStream</code></td><td style="border-bottom: 0.5pt solid ; ">Open a file for reading via an <code class="literal">InputStream</code> or create and open a file
for writing via an <code class="literal">OuputStream</code>. Optionally, specify file
truncation for the output stream; the default is to create a
truncate on write.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">probeContentType()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">String</code></td><td style="border-bottom: 0.5pt solid ; ">Returns the MIME type of the file if it can be determined
by installed <code class="literal">FileTypeDetector</code>
services or <code class="literal">null</code> if
unknown.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">readAllBytes()</code>,
<code class="literal">readAllLines()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">byte[] or <code class="literal">List</code><<code class="literal">String</code>></td><td style="border-bottom: 0.5pt solid ; ">Read all data from the file as a byte [] or all
characters as a list of strings using a specified character
encoding.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">size()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">long</td><td style="border-bottom: 0.5pt solid ; ">Get the size in bytes of the file at the specified
path.</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">walkFileTree()</code></td><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><code class="literal">Path</code></td><td style="border-bottom: 0.5pt solid ; ">Apply a <code class="literal">FileVisitor</code> to
the specified directory tree, optionally specifying whether to
follow links and a maximum depths of traversal.</td></tr><tr><td style="border-right: 0.5pt solid ; "><code class="literal">write()</code></td><td style="border-right: 0.5pt solid ; "><code class="literal">Path</code></td><td style="">Write an array of bytes or a collection of strings (with
a specified character encoding) to the file at the specified
path and close the file, optionally specifying append and
truncation behavior. The default is to truncate and write the
data.</td></tr></tbody></table></div></div><p>With the preceding methods, we can fetch input or output streams
or buffered readers and writers to a given file. We can also create
paths as files and dirctories and iterate through file hierarchies.
We’ll discuss directory operations in the next section.</p><p>As a reminder, the <code class="literal">resolve()</code>
and <code class="literal">resolveSibling()</code> methods of
<code class="literal">Path</code> are useful for constructing
targets for the <code class="literal">copy()</code> and <code class="literal">move()</code> operations.</p><a id="I_programlisting12_id759285"/><pre class="programlisting"><code class="c1">// Move the file /tmp/foo.txt to /tmp/bar.txt</code>
<code class="n">Path</code> <code class="n">foo</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code><code class="s">"/tmp/foo.txt"</code> <code class="o">);</code>
<code class="n">Files</code><code class="o">.</code><code class="na">move</code><code class="o">(</code> <code class="n">foo</code><code class="o">,</code> <code class="n">foo</code><code class="o">.</code><code class="na">resolveSibling</code><code class="o">(</code><code class="s">"bar.txt"</code><code class="o">)</code> <code class="o">);</code></pre><p>For quickly reading and writing the contents of files without
streaming, we can use the <code class="literal">read all</code>
and <code class="literal">write</code> methods that move byte
arrays or strings in and out of files in a single operation. These are
very convenient for files that easily fit into memory.<a id="I_indexterm12_id759307" class="indexterm"/><a id="I_indexterm12_id759314" class="indexterm"/></p><a id="I_programlisting12_id759321"/><pre class="programlisting"><code class="c1">// Read and write collection of String (e.g. lines of text)</code>
<code class="n">Charset</code> <code class="n">asciiCharset</code> <code class="o">=</code> <code class="n">Charset</code><code class="o">.</code><code class="na">forName</code><code class="o">(</code><code class="s">"US-ASCII"</code><code class="o">);</code>
<code class="n">List</code><code class="o"><</code><code class="n">String</code><code class="o">></code> <code class="n">csvData</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">readAllLines</code><code class="o">(</code> <code class="n">csvPath</code><code class="o">,</code> <code class="n">asciiCharset</code> <code class="o">);</code>
<code class="n">Files</code><code class="o">.</code><code class="na">write</code><code class="o">(</code> <code class="n">newCSVPath</code><code class="o">,</code> <code class="n">csvData</code><code class="o">,</code> <code class="n">asciiCharset</code> <code class="o">);</code>
<code class="c1">// Read and write bytes</code>
<code class="kt">byte</code> <code class="o">[]</code> <code class="n">data</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">readAllBytes</code><code class="o">(</code> <code class="n">dataPath</code> <code class="o">);</code>
<code class="n">Files</code><code class="o">.</code><code class="na">write</code><code class="o">(</code> <code class="n">newDataPath</code><code class="o">,</code> <code class="n">data</code> <code class="o">);</code></pre></div><div class="sect2" title="Directory Operations"><div class="titlepage"><div><div><h2 class="title"><a id="id2038581"/>Directory Operations</h2></div></div></div><p><a id="idx10710" class="indexterm"/> <a id="idx10728" class="indexterm"/>In addition to basic directory creation and manipulation
methods of the <code class="literal">Files</code> class, there are
methods for listing the files within a given directory and traversing
all files and directories in a directory tree. To list the files in a
single directory, we can use one of the <a id="I_indexterm12_id759375" class="indexterm"/><code class="literal">newDirectoryStream()</code>
methods, which returns an iterable <a id="I_indexterm12_id759387" class="indexterm"/><code class="literal">DirectoryStream</code>.</p><a id="I_programlisting12_id759397"/><pre class="programlisting"><code class="c1">// Print the files and directories in /tmp</code>
<code class="k">try</code> <code class="o">(</code> <code class="n">DirectoryStream</code><code class="o"><</code><code class="n">Path</code><code class="o">></code> <code class="n">paths</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">newDirectoryStream</code><code class="o">(</code>
<code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">)</code> <code class="o">)</code> <code class="o">)</code> <code class="o">{</code>
<code class="k">for</code> <code class="o">(</code> <code class="n">Path</code> <code class="n">path</code> <code class="o">:</code> <code class="n">paths</code> <code class="o">)</code> <code class="o">{</code> <code class="n">System</code><code class="o">.</code><code class="na">out</code><code class="o">.</code><code class="na">println</code><code class="o">(</code> <code class="n">path</code> <code class="o">);</code> <code class="o">}</code>
<code class="o">}</code></pre><p>The snippet lists the entries in “/tmp,” iterating over the
directory stream to print the results. Note that we open the <code class="literal">DirectoryStream</code> within a <code class="literal">try</code>-with-resources clause so that it is
automatically closed for us. A <code class="literal">DirectoryStream</code> is implemented as a kind of
one-way iterable that is analogous to a stream, and it must be closed to
free up associated resources. The order in which the entries are
returned is not defined by the API and you may need to store and sort
them if ordering is required.</p><p>Another form of <code class="literal">newDirectoryStream()</code> takes a <span class="emphasis"><em>glob
pattern</em></span> to limit the files matched in the listing:</p><a id="I_programlisting12_id759443"/><pre class="programlisting"><code class="c1">// Only files in /tmp matching "*.txt" (globbing)</code>
<code class="k">try</code> <code class="o">(</code> <code class="n">DirectoryStream</code><code class="o"><</code><code class="n">Path</code><code class="o">></code> <code class="n">paths</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">newDirectoryStream</code><code class="o">(</code>
<code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">),</code> <code class="s">"*.txt"</code> <code class="o">)</code> <code class="o">)</code> <code class="o">{</code>
<code class="o">...</code></pre><p>File globbing filters filenames using the familiar “*” and a few
other patterns to specify matching names. <a class="xref" href="ch12s03.html#t1203" title="Table 12-3. File globbing pattern examples">Table 12-3</a>
provides some additional examples of file globbing patterns.<a id="I_indexterm12_id759467" class="indexterm"/></p><div class="table"><a id="t1203"/><p class="title">Table 12-3. File globbing pattern examples</p><div class="table-contents"><table summary="File globbing pattern examples" style="border-collapse: collapse;border-top: 0.5pt solid ; border-bottom: 0.5pt solid ; border-left: 0.5pt solid ; border-right: 0.5pt solid ; "><colgroup><col/><col/></colgroup><thead><tr><th style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Pattern</th><th style="border-bottom: 0.5pt solid ; ">Example</th></tr></thead><tbody><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">*.txt</td><td style="border-bottom: 0.5pt solid ; ">Filenames ending in “.txt”</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">*.{java,class}</td><td style="border-bottom: 0.5pt solid ; ">Filenames ending in “java” or “class”</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">[a,b,c]*</td><td style="border-bottom: 0.5pt solid ; ">Filenames starting with “a”, “b”, or “c”</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">[0-9]*</td><td style="border-bottom: 0.5pt solid ; ">Filenames starting with the digits 0 through 9</td></tr><tr><td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">[!0-9]*</td><td style="border-bottom: 0.5pt solid ; ">Filenames starting with any character except 0 through
9</td></tr><tr><td style="border-right: 0.5pt solid ; ">pass?.dat</td><td style="">Filenames starting with “pass” plus any character plus
“.dat” (e.g., pass1.dat, passN.dat)</td></tr></tbody></table></div></div><p>If globbing patterns are not sufficient, we can provide our own
stream filter by implementing the <code class="literal">DirectoryStream.Filter</code> interface. The
following snippet is the procedural (code) version of the “*.txt” glob
pattern; matching filenames ending with “.txt”. We’ve implemented the
filter as an anonymous inner class here because it’s short:</p><a id="I_programlisting12_id759552"/><pre class="programlisting"><code class="c1">// Same as above using our own (anonymous) filter implementation</code>
<code class="k">try</code> <code class="o">(</code> <code class="n">DirectoryStream</code><code class="o"><</code><code class="n">Path</code><code class="o">></code> <code class="n">paths</code> <code class="o">=</code> <code class="n">Files</code><code class="o">.</code><code class="na">newDirectoryStream</code><code class="o">(</code>
<code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/tmp"</code> <code class="o">),</code>
<code class="k">new</code> <code class="n">DirectoryStream</code><code class="o">.</code><code class="na">Filter</code><code class="o"><</code><code class="n">Path</code><code class="o">>()</code> <code class="o">{</code>
<code class="nd">@Override</code>
<code class="kd">public</code> <code class="kt">boolean</code> <code class="nf">accept</code><code class="o">(</code> <code class="n">Path</code> <code class="n">entry</code> <code class="o">)</code> <code class="kd">throws</code> <code class="n">IOException</code> <code class="o">{</code>
<code class="k">return</code> <code class="n">entry</code><code class="o">.</code><code class="na">toString</code><code class="o">().</code><code class="na">endsWith</code><code class="o">(</code> <code class="s">".txt"</code> <code class="o">);</code>
<code class="o">}</code>
<code class="o">}</code> <code class="o">)</code> <code class="o">)</code> <code class="o">{</code>
<code class="o">...</code></pre><p>Finally, if we need to iterate through a whole directory hierarchy
instead of just a single directory, we can use a <a id="I_indexterm12_id759566" class="indexterm"/><code class="literal">FileVisitor</code>. The
<code class="literal">Files</code><a id="I_indexterm12_id759581" class="indexterm"/><code class="literal">walkFileTree()</code> method
takes a starting path and performs a depth-first traversal of the file
hierarchy, giving the provided <code class="literal">FileVisitor</code> a chance to “visit” each path
element in the tree. The following short snippet prints all file and
directory names under the <span class="emphasis"><em>/Users/pat</em></span> path:</p><a id="I_programlisting12_id759604"/><pre class="programlisting"><code class="c1">// Visit all of the files in a directory tree</code>
<code class="n">Files</code><code class="o">.</code><code class="na">walkFileTree</code><code class="o">(</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code> <code class="s">"/Users/pat"</code><code class="o">),</code> <code class="k">new</code> <code class="n">SimpleFileVisitor</code><code class="o"><</code><code class="n">Path</code><code class="o">>()</code> <code class="o">{</code>
<code class="nd">@Override</code>
<code class="kd">public</code> <code class="n">FileVisitResult</code> <code class="nf">visitFile</code><code class="o">(</code> <code class="n">Path</code> <code class="n">file</code><code class="o">,</code> <code class="n">BasicFileAttributes</code> <code class="n">attrs</code> <code class="o">)</code>
<code class="o">{</code>
<code class="n">System</code><code class="o">.</code><code class="na">out</code><code class="o">.</code><code class="na">println</code><code class="o">(</code> <code class="s">"path = "</code> <code class="o">+</code> <code class="n">file</code> <code class="o">);</code>
<code class="k">return</code> <code class="n">FileVisitResult</code><code class="o">.</code><code class="na">CONTINUE</code><code class="o">;</code>
<code class="o">}</code>
<code class="o">}</code> <code class="o">);</code></pre><p>For each entry in the file tree, our visitor’s <a id="I_indexterm12_id759620" class="indexterm"/><code class="literal">visitFile()</code> method is
invoked with the <code class="literal">Path</code> element and
attributes as arguments. The visitor can perform any action it likes in
relation to the file and then indicate whether or not the traversal
should continue by returning one of a set of enumerated result types:
<code class="literal">FileVisitResult</code><code class="literal">CONTINUE</code> or <code class="literal">TERMINATE</code>. Here we have subclassed the
<code class="literal">SimpleFileVisitor</code>, which is a
convenience class that implements the methods of the <code class="literal">FileVisitor</code> interface for us with no-op
(empty) bodies, allowing us to override only those of interest. Other
methods available include <code class="literal">visitFileFailed()</code>, which is called if a file
or directory cannot be visited (e.g., due to permissions), and the pair
<a id="I_indexterm12_id759673" class="indexterm"/><code class="literal">preVisitDirectory()</code> and
<a id="I_indexterm12_id759684" class="indexterm"/><code class="literal">postVisitDirectory()</code>,
which can be used to perform actions before and after a new directory is
visited. The <code class="literal">preVisitDirectory()</code> has
additional usefulness in that it is allowed to return the value <code class="literal">SKIP_SUBTREE</code> to continue the traversal without
descending into the target path and <code class="literal">SKIP_SIBLINGS</code> value, which indicates that
traversal should continue, skipping the remaining entries at the same
level as the target path.</p><p>As you can see, the file listing and traversal methods of the NIO
File package are much more sophisticated than those of the classic
<code class="literal">java.io</code> API and are a welcome
addition.<a id="I_indexterm12_id759724" class="indexterm"/><a id="I_indexterm12_id759731" class="indexterm"/></p></div><div class="sect2" title="Watching Paths"><div class="titlepage"><div><div><h2 class="title"><a id="id2038584"/>Watching Paths</h2></div></div></div><p><a id="idx10713" class="indexterm"/> <a id="idx10731" class="indexterm"/>One of the nicest features of the NIO File API is the
<a id="I_indexterm12_id759770" class="indexterm"/><code class="literal">WatchService</code>, which can
monitor a <code class="literal">Path</code> for changes to any
file or directory in the hierarchy. We can choose to receive events when
files or directories are added, modified, or deleted. The following
snippet watches for changes under the folder
<span class="emphasis"><em>/Users/pat</em></span>:</p><a id="I_programlisting12_id759791"/><pre class="programlisting"><code class="n">Path</code> <code class="n">watchPath</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">getPath</code><code class="o">(</code><code class="s">"/Users/pat"</code><code class="o">);</code>
<code class="n">WatchService</code> <code class="n">watchService</code> <code class="o">=</code> <code class="n">fs</code><code class="o">.</code><code class="na">newWatchService</code><code class="o">();</code>
<code class="n">watchPath</code><code class="o">.</code><code class="na">register</code><code class="o">(</code> <code class="n">watchService</code><code class="o">,</code> <code class="n">ENTRY_CREATE</code><code class="o">,</code> <code class="n">ENTRY_MODIFY</code><code class="o">,</code> <code class="n">ENTRY_DELETE</code> <code class="o">);</code>
<code class="k">while</code><code class="o">(</code> <code class="kc">true</code> <code class="o">)</code>
<code class="o">{</code>
<code class="n">WatchKey</code> <code class="n">changeKey</code> <code class="o">=</code> <code class="n">watchService</code><code class="o">.</code><code class="na">take</code><code class="o">();</code>
<code class="n">List</code><code class="o"><</code><code class="n">WatchEvent</code><code class="o"><?>></code> <code class="n">watchEvents</code> <code class="o">=</code> <code class="n">changeKey</code><code class="o">.</code><code class="na">pollEvents</code><code class="o">();</code>
<code class="k">for</code> <code class="o">(</code> <code class="n">WatchEvent</code><code class="o"><?></code> <code class="n">watchEvent</code> <code class="o">:</code> <code class="n">watchEvents</code> <code class="o">)</code>
<code class="o">{</code>
<code class="c1">// Ours are all Path type events:</code>
<code class="n">WatchEvent</code><code class="o"><</code><code class="n">Path</code><code class="o">></code> <code class="n">pathEvent</code> <code class="o">=</code> <code class="o">(</code><code class="n">WatchEvent</code><code class="o"><</code><code class="n">Path</code><code class="o">>)</code><code class="n">watchEvent</code><code class="o">;</code>
<code class="n">Path</code> <code class="n">path</code> <code class="o">=</code> <code class="n">pathEvent</code><code class="o">.</code><code class="na">context</code><code class="o">();</code>
<code class="n">WatchEvent</code><code class="o">.</code><code class="na">Kind</code><code class="o"><</code><code class="n">Path</code><code class="o">></code> <code class="n">eventKind</code> <code class="o">=</code> <code class="n">pathEvent</code><code class="o">.</code><code class="na">kind</code><code class="o">();</code>
<code class="n">System</code><code class="o">.</code><code class="na">out</code><code class="o">.</code><code class="na">println</code><code class="o">(</code> <code class="n">eventKind</code> <code class="o">+</code> <code class="s">" f