893N/A/*
3909N/A * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
893N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
893N/A *
893N/A * This code is free software; you can redistribute it and/or modify it
893N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
893N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
893N/A *
893N/A * This code is distributed in the hope that it will be useful, but WITHOUT
893N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
893N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
893N/A * version 2 for more details (a copy is included in the LICENSE file that
893N/A * accompanied this code).
893N/A *
893N/A * You should have received a copy of the GNU General Public License version
893N/A * 2 along with this work; if not, write to the Free Software Foundation,
893N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
893N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
893N/A */
893N/A
893N/Apackage java.nio.file;
893N/A
3471N/Aimport java.nio.file.attribute.*;
3471N/Aimport java.nio.file.spi.FileSystemProvider;
893N/Aimport java.nio.file.spi.FileTypeDetector;
3471N/Aimport java.nio.channels.SeekableByteChannel;
3471N/Aimport java.io.InputStream;
3471N/Aimport java.io.OutputStream;
3471N/Aimport java.io.Reader;
3471N/Aimport java.io.Writer;
3471N/Aimport java.io.BufferedReader;
3471N/Aimport java.io.BufferedWriter;
3471N/Aimport java.io.InputStreamReader;
3471N/Aimport java.io.OutputStreamWriter;
893N/Aimport java.io.IOException;
893N/Aimport java.util.*;
893N/Aimport java.security.AccessController;
893N/Aimport java.security.PrivilegedAction;
3471N/Aimport java.nio.charset.Charset;
3471N/Aimport java.nio.charset.CharsetDecoder;
3471N/Aimport java.nio.charset.CharsetEncoder;
893N/A
893N/A/**
3471N/A * This class consists exclusively of static methods that operate on files,
3471N/A * directories, or other types of files.
3471N/A *
3471N/A * <p> In most cases, the methods defined here will delegate to the associated
3471N/A * file system provider to perform the file operations.
893N/A *
893N/A * @since 1.7
893N/A */
893N/A
893N/Apublic final class Files {
893N/A private Files() { }
893N/A
3471N/A /**
3471N/A * Returns the {@code FileSystemProvider} to delegate to.
3471N/A */
3471N/A private static FileSystemProvider provider(Path path) {
3471N/A return path.getFileSystem().provider();
3471N/A }
3471N/A
3471N/A // -- File contents --
3471N/A
3471N/A /**
3471N/A * Opens a file, returning an input stream to read from the file. The stream
3471N/A * will not be buffered, and is not required to support the {@link
3471N/A * InputStream#mark mark} or {@link InputStream#reset reset} methods. The
3471N/A * stream will be safe for access by multiple concurrent threads. Reading
3471N/A * commences at the beginning of the file. Whether the returned stream is
3471N/A * <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly
3471N/A * file system provider specific and therefore not specified.
3471N/A *
3471N/A * <p> The {@code options} parameter determines how the file is opened.
3471N/A * If no options are present then it is equivalent to opening the file with
3471N/A * the {@link StandardOpenOption#READ READ} option. In addition to the {@code
3471N/A * READ} option, an implementation may also support additional implementation
3471N/A * specific options.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to open
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return a new input stream
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if an invalid combination of options is specified
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported option is specified
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
3471N/A */
3471N/A public static InputStream newInputStream(Path path, OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return provider(path).newInputStream(path, options);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens or creates a file, returning an output stream that may be used to
3471N/A * write bytes to the file. The resulting stream will not be buffered. The
3471N/A * stream will be safe for access by multiple concurrent threads. Whether
3471N/A * the returned stream is <i>asynchronously closeable</i> and/or
3471N/A * <i>interruptible</i> is highly file system provider specific and
3471N/A * therefore not specified.
3471N/A *
3471N/A * <p> This method opens or creates a file in exactly the manner specified
3471N/A * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}
3471N/A * method with the exception that the {@link StandardOpenOption#READ READ}
3471N/A * option may not be present in the array of options. If no options are
3471N/A * present then this method works as if the {@link StandardOpenOption#CREATE
3471N/A * CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING},
3471N/A * and {@link StandardOpenOption#WRITE WRITE} options are present. In other
3471N/A * words, it opens the file for writing, creating the file if it doesn't
3471N/A * exist, or initially truncating an existing {@link #isRegularFile
3471N/A * regular-file} to a size of {@code 0} if it exists.
3471N/A *
3471N/A * <p> <b>Usage Examples:</b>
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A *
3642N/A * // truncate and overwrite an existing file, or create the file if
3642N/A * // it doesn't initially exist
3471N/A * OutputStream out = Files.newOutputStream(path);
3471N/A *
3471N/A * // append to an existing file, fail if the file does not exist
3471N/A * out = Files.newOutputStream(path, APPEND);
3471N/A *
3471N/A * // append to an existing file, create file if it doesn't initially exist
3642N/A * out = Files.newOutputStream(path, CREATE, APPEND);
3471N/A *
3471N/A * // always create new file, failing if it already exists
3642N/A * out = Files.newOutputStream(path, CREATE_NEW);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to open or create
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return a new output stream
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if {@code options} contains an invalid combination of options
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported option is specified
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file. The {@link
3471N/A * SecurityManager#checkDelete(String) checkDelete} method is
3471N/A * invoked to check delete access if the file is opened with the
3471N/A * {@code DELETE_ON_CLOSE} option.
3471N/A */
3471N/A public static OutputStream newOutputStream(Path path, OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return provider(path).newOutputStream(path, options);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens or creates a file, returning a seekable byte channel to access the
3471N/A * file.
3471N/A *
3471N/A * <p> The {@code options} parameter determines how the file is opened.
3471N/A * The {@link StandardOpenOption#READ READ} and {@link
3471N/A * StandardOpenOption#WRITE WRITE} options determine if the file should be
3471N/A * opened for reading and/or writing. If neither option (or the {@link
3471N/A * StandardOpenOption#APPEND APPEND} option) is present then the file is
3471N/A * opened for reading. By default reading or writing commence at the
3471N/A * beginning of the file.
3471N/A *
3471N/A * <p> In the addition to {@code READ} and {@code WRITE}, the following
3471N/A * options may be present:
3471N/A *
3471N/A * <table border=1 cellpadding=5 summary="">
3471N/A * <tr> <th>Option</th> <th>Description</th> </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardOpenOption#APPEND APPEND} </td>
3471N/A * <td> If this option is present then the file is opened for writing and
3471N/A * each invocation of the channel's {@code write} method first advances
3471N/A * the position to the end of the file and then writes the requested
3471N/A * data. Whether the advancement of the position and the writing of the
3471N/A * data are done in a single atomic operation is system-dependent and
3471N/A * therefore unspecified. This option may not be used in conjunction
3471N/A * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>
3471N/A * <td> If this option is present then the existing file is truncated to
3471N/A * a size of 0 bytes. This option is ignored when the file is opened only
3471N/A * for reading. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>
3471N/A * <td> If this option is present then a new file is created, failing if
3471N/A * the file already exists or is a symbolic link. When creating a file the
3471N/A * check for the existence of the file and the creation of the file if it
3471N/A * does not exist is atomic with respect to other file system operations.
3471N/A * This option is ignored when the file is opened only for reading. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td > {@link StandardOpenOption#CREATE CREATE} </td>
3471N/A * <td> If this option is present then an existing file is opened if it
3471N/A * exists, otherwise a new file is created. This option is ignored if the
3471N/A * {@code CREATE_NEW} option is also present or the file is opened only
3471N/A * for reading. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>
3471N/A * <td> When this option is present then the implementation makes a
3471N/A * <em>best effort</em> attempt to delete the file when closed by the
3471N/A * {@link SeekableByteChannel#close close} method. If the {@code close}
3471N/A * method is not invoked then a <em>best effort</em> attempt is made to
3471N/A * delete the file when the Java virtual machine terminates. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td>{@link StandardOpenOption#SPARSE SPARSE} </td>
3471N/A * <td> When creating a new file this option is a <em>hint</em> that the
3471N/A * new file will be sparse. This option is ignored when not creating
3471N/A * a new file. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardOpenOption#SYNC SYNC} </td>
3471N/A * <td> Requires that every update to the file's content or metadata be
3471N/A * written synchronously to the underlying storage device. (see <a
3471N/A * href="package-summary.html#integrity"> Synchronized I/O file
3471N/A * integrity</a>). </td>
3471N/A * <tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardOpenOption#DSYNC DSYNC} </td>
3471N/A * <td> Requires that every update to the file's content be written
3471N/A * synchronously to the underlying storage device. (see <a
3471N/A * href="package-summary.html#integrity"> Synchronized I/O file
3471N/A * integrity</a>). </td>
3471N/A * </tr>
3471N/A * </table>
3471N/A *
3471N/A * <p> An implementation may also support additional implementation specific
3471N/A * options.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when a new file is created.
3471N/A *
3471N/A * <p> In the case of the default provider, the returned seekable byte channel
3471N/A * is a {@link java.nio.channels.FileChannel}.
3471N/A *
3471N/A * <p> <b>Usage Examples:</b>
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A *
3471N/A * // open file for reading
3471N/A * ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ)));
3471N/A *
3471N/A * // open file for writing to the end of an existing file, creating
3471N/A * // the file if it doesn't already exist
3471N/A * WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND));
3471N/A *
3471N/A * // create file with initial permissions, opening it for both reading and writing
3471N/A * {@code FileAttribute<<SetPosixFilePermission>> perms = ...}
3471N/A * SeekableByteChannel sbc = Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to open or create
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the file
3471N/A *
3471N/A * @return a new seekable byte channel
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the set contains an invalid combination of options
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported open option is specified or the array contains
3471N/A * attributes that cannot be set atomically when creating the file
3471N/A * @throws FileAlreadyExistsException
3471N/A * if a file of that name already exists and the {@link
3471N/A * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
3471N/A * <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the path if the file is
3471N/A * opened for reading. The {@link SecurityManager#checkWrite(String)
3471N/A * checkWrite} method is invoked to check write access to the path
3471N/A * if the file is opened for writing. The {@link
3471N/A * SecurityManager#checkDelete(String) checkDelete} method is
3471N/A * invoked to check delete access if the file is opened with the
3471N/A * {@code DELETE_ON_CLOSE} option.
3471N/A *
3471N/A * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[])
3471N/A */
3471N/A public static SeekableByteChannel newByteChannel(Path path,
3471N/A Set<? extends OpenOption> options,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A return provider(path).newByteChannel(path, options, attrs);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens or creates a file, returning a seekable byte channel to access the
3471N/A * file.
3471N/A *
3471N/A * <p> This method opens or creates a file in exactly the manner specified
3471N/A * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}
3471N/A * method.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to open or create
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return a new seekable byte channel
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the set contains an invalid combination of options
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported open option is specified
3471N/A * @throws FileAlreadyExistsException
3471N/A * if a file of that name already exists and the {@link
3471N/A * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
3471N/A * <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the path if the file is
3471N/A * opened for reading. The {@link SecurityManager#checkWrite(String)
3471N/A * checkWrite} method is invoked to check write access to the path
3471N/A * if the file is opened for writing. The {@link
3471N/A * SecurityManager#checkDelete(String) checkDelete} method is
3471N/A * invoked to check delete access if the file is opened with the
3471N/A * {@code DELETE_ON_CLOSE} option.
3471N/A *
3471N/A * @see java.nio.channels.FileChannel#open(Path,OpenOption[])
3471N/A */
3471N/A public static SeekableByteChannel newByteChannel(Path path, OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A Set<OpenOption> set = new HashSet<OpenOption>(options.length);
3471N/A Collections.addAll(set, options);
3471N/A return newByteChannel(path, set);
3471N/A }
3471N/A
3471N/A // -- Directories --
3471N/A
5022N/A private static class AcceptAllFilter
5022N/A implements DirectoryStream.Filter<Path>
5022N/A {
5022N/A private AcceptAllFilter() { }
5022N/A
5022N/A @Override
5022N/A public boolean accept(Path entry) { return true; }
5022N/A
5022N/A static final AcceptAllFilter FILTER = new AcceptAllFilter();
5022N/A }
5022N/A
3471N/A /**
3471N/A * Opens a directory, returning a {@link DirectoryStream} to iterate over
3471N/A * all entries in the directory. The elements returned by the directory
3471N/A * stream's {@link DirectoryStream#iterator iterator} are of type {@code
3471N/A * Path}, each one representing an entry in the directory. The {@code Path}
3471N/A * objects are obtained as if by {@link Path#resolve(Path) resolving} the
3471N/A * name of the directory entry against {@code dir}.
3471N/A *
3471N/A * <p> When not using the try-with-resources construct, then directory
3471N/A * stream's {@code close} method should be invoked after iteration is
3471N/A * completed so as to free any resources held for the open directory.
3471N/A *
3471N/A * <p> When an implementation supports operations on entries in the
3471N/A * directory that execute in a race-free manner then the returned directory
3471N/A * stream is a {@link SecureDirectoryStream}.
3471N/A *
3471N/A * @param dir
3471N/A * the path to the directory
3471N/A *
3471N/A * @return a new and open {@code DirectoryStream} object
3471N/A *
3471N/A * @throws NotDirectoryException
3471N/A * if the file could not otherwise be opened because it is not
3471N/A * a directory <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the directory.
3471N/A */
3471N/A public static DirectoryStream<Path> newDirectoryStream(Path dir)
3471N/A throws IOException
3471N/A {
5022N/A return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens a directory, returning a {@link DirectoryStream} to iterate over
3471N/A * the entries in the directory. The elements returned by the directory
3471N/A * stream's {@link DirectoryStream#iterator iterator} are of type {@code
3471N/A * Path}, each one representing an entry in the directory. The {@code Path}
3471N/A * objects are obtained as if by {@link Path#resolve(Path) resolving} the
3471N/A * name of the directory entry against {@code dir}. The entries returned by
3471N/A * the iterator are filtered by matching the {@code String} representation
3471N/A * of their file names against the given <em>globbing</em> pattern.
3471N/A *
3471N/A * <p> For example, suppose we want to iterate over the files ending with
3471N/A * ".java" in a directory:
3471N/A * <pre>
3471N/A * Path dir = ...
3471N/A * try (DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(dir, "*.java")) {
3471N/A * :
3471N/A * }
3471N/A * </pre>
3471N/A *
3471N/A * <p> The globbing pattern is specified by the {@link
3471N/A * FileSystem#getPathMatcher getPathMatcher} method.
3471N/A *
3471N/A * <p> When not using the try-with-resources construct, then directory
3471N/A * stream's {@code close} method should be invoked after iteration is
3471N/A * completed so as to free any resources held for the open directory.
3471N/A *
3471N/A * <p> When an implementation supports operations on entries in the
3471N/A * directory that execute in a race-free manner then the returned directory
3471N/A * stream is a {@link SecureDirectoryStream}.
3471N/A *
3471N/A * @param dir
3471N/A * the path to the directory
3471N/A * @param glob
3471N/A * the glob pattern
3471N/A *
3471N/A * @return a new and open {@code DirectoryStream} object
3471N/A *
3471N/A * @throws java.util.regex.PatternSyntaxException
3471N/A * if the pattern is invalid
3471N/A * @throws NotDirectoryException
3471N/A * if the file could not otherwise be opened because it is not
3471N/A * a directory <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the directory.
3471N/A */
3471N/A public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob)
3471N/A throws IOException
3471N/A {
3471N/A // avoid creating a matcher if all entries are required.
3471N/A if (glob.equals("*"))
3471N/A return newDirectoryStream(dir);
3471N/A
3471N/A // create a matcher and return a filter that uses it.
3471N/A FileSystem fs = dir.getFileSystem();
3471N/A final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
3471N/A DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
3471N/A @Override
3471N/A public boolean accept(Path entry) {
3471N/A return matcher.matches(entry.getFileName());
3471N/A }
3471N/A };
3471N/A return fs.provider().newDirectoryStream(dir, filter);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens a directory, returning a {@link DirectoryStream} to iterate over
3471N/A * the entries in the directory. The elements returned by the directory
3471N/A * stream's {@link DirectoryStream#iterator iterator} are of type {@code
3471N/A * Path}, each one representing an entry in the directory. The {@code Path}
3471N/A * objects are obtained as if by {@link Path#resolve(Path) resolving} the
3471N/A * name of the directory entry against {@code dir}. The entries returned by
3471N/A * the iterator are filtered by the given {@link DirectoryStream.Filter
3471N/A * filter}.
3471N/A *
3471N/A * <p> When not using the try-with-resources construct, then directory
3471N/A * stream's {@code close} method should be invoked after iteration is
3471N/A * completed so as to free any resources held for the open directory.
3471N/A *
3471N/A * <p> Where the filter terminates due to an uncaught error or runtime
3471N/A * exception then it is propagated to the {@link Iterator#hasNext()
3471N/A * hasNext} or {@link Iterator#next() next} method. Where an {@code
3471N/A * IOException} is thrown, it results in the {@code hasNext} or {@code
3471N/A * next} method throwing a {@link DirectoryIteratorException} with the
3471N/A * {@code IOException} as the cause.
3471N/A *
3471N/A * <p> When an implementation supports operations on entries in the
3471N/A * directory that execute in a race-free manner then the returned directory
3471N/A * stream is a {@link SecureDirectoryStream}.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to iterate over the files in a directory that are
3471N/A * larger than 8K.
3471N/A * <pre>
3471N/A * DirectoryStream.Filter&lt;Path&gt; filter = new DirectoryStream.Filter&lt;Path&gt;() {
3471N/A * public boolean accept(Path file) throws IOException {
3471N/A * return (Files.size(file) > 8192L);
3471N/A * }
3471N/A * };
3471N/A * Path dir = ...
3471N/A * try (DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(dir, filter)) {
3471N/A * :
3471N/A * }
3471N/A * </pre>
3471N/A *
3471N/A * @param dir
3471N/A * the path to the directory
3471N/A * @param filter
3471N/A * the directory stream filter
3471N/A *
3471N/A * @return a new and open {@code DirectoryStream} object
3471N/A *
3471N/A * @throws NotDirectoryException
3471N/A * if the file could not otherwise be opened because it is not
3471N/A * a directory <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the directory.
3471N/A */
3471N/A public static DirectoryStream<Path> newDirectoryStream(Path dir,
3471N/A DirectoryStream.Filter<? super Path> filter)
3471N/A throws IOException
3471N/A {
3471N/A return provider(dir).newDirectoryStream(dir, filter);
3471N/A }
3471N/A
3471N/A // -- Creation and deletion --
3471N/A
3471N/A /**
3471N/A * Creates a new and empty file, failing if the file already exists. The
3471N/A * check for the existence of the file and the creation of the new file if
3471N/A * it does not exist are a single operation that is atomic with respect to
3471N/A * all other filesystem activities that might affect the directory.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when creating the file. Each attribute
3471N/A * is identified by its {@link FileAttribute#name name}. If more than one
3471N/A * attribute of the same name is included in the array then all but the last
3471N/A * occurrence is ignored.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to create
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the file
3471N/A *
3471N/A * @return the file
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the file
3471N/A * @throws FileAlreadyExistsException
3471N/A * if a file of that name already exists
3471N/A * <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or the parent directory does not exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the new file.
3471N/A */
3471N/A public static Path createFile(Path path, FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A EnumSet<StandardOpenOption> options =
3471N/A EnumSet.<StandardOpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
3471N/A newByteChannel(path, options, attrs).close();
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a new directory. The check for the existence of the file and the
3471N/A * creation of the directory if it does not exist are a single operation
3471N/A * that is atomic with respect to all other filesystem activities that might
3471N/A * affect the directory. The {@link #createDirectories createDirectories}
3471N/A * method should be used where it is required to create all nonexistent
3471N/A * parent directories first.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when creating the directory. Each
3471N/A * attribute is identified by its {@link FileAttribute#name name}. If more
3471N/A * than one attribute of the same name is included in the array then all but
3471N/A * the last occurrence is ignored.
3471N/A *
3471N/A * @param dir
3471N/A * the directory to create
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the directory
3471N/A *
3471N/A * @return the directory
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws FileAlreadyExistsException
3471N/A * if a directory could not otherwise be created because a file of
3471N/A * that name already exists <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or the parent directory does not exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the new directory.
3471N/A */
3471N/A public static Path createDirectory(Path dir, FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A provider(dir).createDirectory(dir, attrs);
3471N/A return dir;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a directory by creating all nonexistent parent directories first.
3471N/A * Unlike the {@link #createDirectory createDirectory} method, an exception
3471N/A * is not thrown if the directory could not be created because it already
3471N/A * exists.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when creating the nonexistent
3471N/A * directories. Each file attribute is identified by its {@link
3471N/A * FileAttribute#name name}. If more than one attribute of the same name is
3471N/A * included in the array then all but the last occurrence is ignored.
3471N/A *
3471N/A * <p> If this method fails, then it may do so after creating some, but not
3471N/A * all, of the parent directories.
3471N/A *
3471N/A * @param dir
3471N/A * the directory to create
3471N/A *
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the directory
3471N/A *
3471N/A * @return the directory
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws FileAlreadyExistsException
3471N/A * if {@code dir} exists but is not a directory <i>(optional specific
3471N/A * exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * in the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked prior to attempting to create a directory and
3471N/A * its {@link SecurityManager#checkRead(String) checkRead} is
3471N/A * invoked for each parent directory that is checked. If {@code
3471N/A * dir} is not an absolute path then its {@link Path#toAbsolutePath
3471N/A * toAbsolutePath} may need to be invoked to get its absolute path.
3471N/A * This may invoke the security manager's {@link
3471N/A * SecurityManager#checkPropertyAccess(String) checkPropertyAccess}
3471N/A * method to check access to the system property {@code user.dir}
3471N/A */
3471N/A public static Path createDirectories(Path dir, FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A // attempt to create the directory
3471N/A try {
3471N/A createAndCheckIsDirectory(dir, attrs);
3471N/A return dir;
3471N/A } catch (FileAlreadyExistsException x) {
3471N/A // file exists and is not a directory
3471N/A throw x;
3471N/A } catch (IOException x) {
3471N/A // parent may not exist or other reason
3471N/A }
3471N/A SecurityException se = null;
3471N/A try {
3471N/A dir = dir.toAbsolutePath();
3471N/A } catch (SecurityException x) {
3471N/A // don't have permission to get absolute path
3471N/A se = x;
3471N/A }
3471N/A // find a decendent that exists
3471N/A Path parent = dir.getParent();
3471N/A while (parent != null) {
3471N/A try {
3471N/A provider(parent).checkAccess(parent);
3471N/A break;
3471N/A } catch (NoSuchFileException x) {
3471N/A // does not exist
3471N/A }
3471N/A parent = parent.getParent();
3471N/A }
3471N/A if (parent == null) {
3471N/A // unable to find existing parent
3471N/A if (se != null)
3471N/A throw se;
3471N/A throw new IOException("Root directory does not exist");
3471N/A }
3471N/A
3471N/A // create directories
3471N/A Path child = parent;
3471N/A for (Path name: parent.relativize(dir)) {
3471N/A child = child.resolve(name);
3471N/A createAndCheckIsDirectory(child, attrs);
3471N/A }
3471N/A return dir;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Used by createDirectories to attempt to create a directory. A no-op
3471N/A * if the directory already exists.
3471N/A */
3471N/A private static void createAndCheckIsDirectory(Path dir,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A try {
3471N/A createDirectory(dir, attrs);
3471N/A } catch (FileAlreadyExistsException x) {
3471N/A if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS))
3471N/A throw x;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a new empty file in the specified directory, using the given
3471N/A * prefix and suffix strings to generate its name. The resulting
3471N/A * {@code Path} is associated with the same {@code FileSystem} as the given
3471N/A * directory.
3471N/A *
3471N/A * <p> The details as to how the name of the file is constructed is
3471N/A * implementation dependent and therefore not specified. Where possible
3471N/A * the {@code prefix} and {@code suffix} are used to construct candidate
3471N/A * names in the same manner as the {@link
3471N/A * java.io.File#createTempFile(String,String,File)} method.
3471N/A *
3471N/A * <p> As with the {@code File.createTempFile} methods, this method is only
3471N/A * part of a temporary-file facility. Where used as a <em>work files</em>,
3471N/A * the resulting file may be opened using the {@link
3471N/A * StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the
3471N/A * file is deleted when the appropriate {@code close} method is invoked.
3471N/A * Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the
3471N/A * {@link java.io.File#deleteOnExit} mechanism may be used to delete the
3471N/A * file automatically.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when creating the file. Each attribute
3471N/A * is identified by its {@link FileAttribute#name name}. If more than one
3471N/A * attribute of the same name is included in the array then all but the last
3471N/A * occurrence is ignored. When no file attributes are specified, then the
3471N/A * resulting file may have more restrictive access permissions to files
3471N/A * created by the {@link java.io.File#createTempFile(String,String,File)}
3471N/A * method.
3471N/A *
3471N/A * @param dir
3471N/A * the path to directory in which to create the file
3471N/A * @param prefix
3471N/A * the prefix string to be used in generating the file's name;
3471N/A * may be {@code null}
3471N/A * @param suffix
3471N/A * the suffix string to be used in generating the file's name;
3471N/A * may be {@code null}, in which case "{@code .tmp}" is used
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the file
3471N/A *
3471N/A * @return the path to the newly created file that did not exist before
3471N/A * this method was invoked
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the prefix or suffix parameters cannot be used to generate
3471N/A * a candidate file name
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or {@code dir} does not exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file.
3471N/A */
3471N/A public static Path createTempFile(Path dir,
3471N/A String prefix,
3471N/A String suffix,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3661N/A return TempFileHelper.createTempFile(Objects.requireNonNull(dir),
3661N/A prefix, suffix, attrs);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates an empty file in the default temporary-file directory, using
3471N/A * the given prefix and suffix to generate its name. The resulting {@code
3471N/A * Path} is associated with the default {@code FileSystem}.
3471N/A *
3471N/A * <p> This method works in exactly the manner specified by the
3471N/A * {@link #createTempFile(Path,String,String,FileAttribute[])} method for
3471N/A * the case that the {@code dir} parameter is the temporary-file directory.
3471N/A *
3471N/A * @param prefix
3471N/A * the prefix string to be used in generating the file's name;
3471N/A * may be {@code null}
3471N/A * @param suffix
3471N/A * the suffix string to be used in generating the file's name;
3471N/A * may be {@code null}, in which case "{@code .tmp}" is used
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the file
3471N/A *
3471N/A * @return the path to the newly created file that did not exist before
3471N/A * this method was invoked
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the prefix or suffix parameters cannot be used to generate
3471N/A * a candidate file name
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or the temporary-file directory does not
3471N/A * exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file.
3471N/A */
3471N/A public static Path createTempFile(String prefix,
3471N/A String suffix,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A return TempFileHelper.createTempFile(null, prefix, suffix, attrs);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a new directory in the specified directory, using the given
3471N/A * prefix to generate its name. The resulting {@code Path} is associated
3471N/A * with the same {@code FileSystem} as the given directory.
3471N/A *
3471N/A * <p> The details as to how the name of the directory is constructed is
3471N/A * implementation dependent and therefore not specified. Where possible
3471N/A * the {@code prefix} is used to construct candidate names.
3471N/A *
3471N/A * <p> As with the {@code createTempFile} methods, this method is only
3471N/A * part of a temporary-file facility. A {@link Runtime#addShutdownHook
3471N/A * shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be
3471N/A * used to delete the directory automatically.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * file-attributes} to set atomically when creating the directory. Each
3471N/A * attribute is identified by its {@link FileAttribute#name name}. If more
3471N/A * than one attribute of the same name is included in the array then all but
3471N/A * the last occurrence is ignored.
3471N/A *
3471N/A * @param dir
3471N/A * the path to directory in which to create the directory
3471N/A * @param prefix
3471N/A * the prefix string to be used in generating the directory's name;
3471N/A * may be {@code null}
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the directory
3471N/A *
3471N/A * @return the path to the newly created directory that did not exist before
3471N/A * this method was invoked
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the prefix cannot be used to generate a candidate directory name
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or {@code dir} does not exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access when creating the
3471N/A * directory.
3471N/A */
3471N/A public static Path createTempDirectory(Path dir,
3471N/A String prefix,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3661N/A return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir),
3661N/A prefix, attrs);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a new directory in the default temporary-file directory, using
3642N/A * the given prefix to generate its name. The resulting {@code Path} is
3642N/A * associated with the default {@code FileSystem}.
3471N/A *
3471N/A * <p> This method works in exactly the manner specified by {@link
3471N/A * #createTempDirectory(Path,String,FileAttribute[])} method for the case
3471N/A * that the {@code dir} parameter is the temporary-file directory.
3471N/A *
3471N/A * @param prefix
3471N/A * the prefix string to be used in generating the directory's name;
3471N/A * may be {@code null}
3471N/A * @param attrs
3471N/A * an optional list of file attributes to set atomically when
3471N/A * creating the directory
3471N/A *
3471N/A * @return the path to the newly created directory that did not exist before
3471N/A * this method was invoked
3471N/A *
3471N/A * @throws IllegalArgumentException
3471N/A * if the prefix cannot be used to generate a candidate directory name
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains an attribute that cannot be set atomically
3471N/A * when creating the directory
3471N/A * @throws IOException
3471N/A * if an I/O error occurs or the temporary-file directory does not
3471N/A * exist
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access when creating the
3471N/A * directory.
3471N/A */
3471N/A public static Path createTempDirectory(String prefix,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A return TempFileHelper.createTempDirectory(null, prefix, attrs);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a symbolic link to a target <i>(optional operation)</i>.
3471N/A *
3471N/A * <p> The {@code target} parameter is the target of the link. It may be an
3471N/A * {@link Path#isAbsolute absolute} or relative path and may not exist. When
3471N/A * the target is a relative path then file system operations on the resulting
3471N/A * link are relative to the path of the link.
3471N/A *
3471N/A * <p> The {@code attrs} parameter is optional {@link FileAttribute
3471N/A * attributes} to set atomically when creating the link. Each attribute is
3471N/A * identified by its {@link FileAttribute#name name}. If more than one attribute
3471N/A * of the same name is included in the array then all but the last occurrence
3471N/A * is ignored.
3471N/A *
3471N/A * <p> Where symbolic links are supported, but the underlying {@link FileStore}
3471N/A * does not support symbolic links, then this may fail with an {@link
3471N/A * IOException}. Additionally, some operating systems may require that the
3471N/A * Java virtual machine be started with implementation specific privileges to
3471N/A * create symbolic links, in which case this method may throw {@code IOException}.
3471N/A *
3471N/A * @param link
3471N/A * the path of the symbolic link to create
3471N/A * @param target
3471N/A * the target of the symbolic link
3471N/A * @param attrs
3471N/A * the array of attributes to set atomically when creating the
3471N/A * symbolic link
3471N/A *
3471N/A * @return the path to the symbolic link
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the implementation does not support symbolic links or the
3471N/A * array contains an attribute that cannot be set atomically when
3471N/A * creating the symbolic link
3471N/A * @throws FileAlreadyExistsException
3471N/A * if a file with the name already exists <i>(optional specific
3471N/A * exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager
3471N/A * is installed, it denies {@link LinkPermission}<tt>("symbolic")</tt>
3471N/A * or its {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method denies write access to the path of the symbolic link.
3471N/A */
3471N/A public static Path createSymbolicLink(Path link, Path target,
3471N/A FileAttribute<?>... attrs)
3471N/A throws IOException
3471N/A {
3471N/A provider(link).createSymbolicLink(link, target, attrs);
3471N/A return link;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Creates a new link (directory entry) for an existing file <i>(optional
3471N/A * operation)</i>.
3471N/A *
3471N/A * <p> The {@code link} parameter locates the directory entry to create.
3471N/A * The {@code existing} parameter is the path to an existing file. This
3471N/A * method creates a new directory entry for the file so that it can be
3471N/A * accessed using {@code link} as the path. On some file systems this is
3471N/A * known as creating a "hard link". Whether the file attributes are
3471N/A * maintained for the file or for each directory entry is file system
3471N/A * specific and therefore not specified. Typically, a file system requires
3471N/A * that all links (directory entries) for a file be on the same file system.
3471N/A * Furthermore, on some platforms, the Java virtual machine may require to
3471N/A * be started with implementation specific privileges to create hard links
3471N/A * or to create links to directories.
3471N/A *
3471N/A * @param link
3471N/A * the link (directory entry) to create
3471N/A * @param existing
3471N/A * a path to an existing file
3471N/A *
3471N/A * @return the path to the link (directory entry)
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the implementation does not support adding an existing file
3471N/A * to a directory
3471N/A * @throws FileAlreadyExistsException
3471N/A * if the entry could not otherwise be created because a file of
3471N/A * that name already exists <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager
3471N/A * is installed, it denies {@link LinkPermission}<tt>("hard")</tt>
3471N/A * or its {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method denies write access to either the link or the
3471N/A * existing file.
3471N/A */
3471N/A public static Path createLink(Path link, Path existing) throws IOException {
3471N/A provider(link).createLink(link, existing);
3471N/A return link;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Deletes a file.
3471N/A *
3471N/A * <p> An implementation may require to examine the file to determine if the
3471N/A * file is a directory. Consequently this method may not be atomic with respect
3471N/A * to other file system operations. If the file is a symbolic link then the
3471N/A * symbolic link itself, not the final target of the link, is deleted.
3471N/A *
3471N/A * <p> If the file is a directory then the directory must be empty. In some
3471N/A * implementations a directory has entries for special files or links that
3471N/A * are created when the directory is created. In such implementations a
3471N/A * directory is considered empty when only the special entries exist.
3471N/A * This method can be used with the {@link #walkFileTree walkFileTree}
3471N/A * method to delete a directory and all entries in the directory, or an
3471N/A * entire <i>file-tree</i> where required.
3471N/A *
3471N/A * <p> On some operating systems it may not be possible to remove a file when
3471N/A * it is open and in use by this Java virtual machine or other programs.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to delete
3471N/A *
3471N/A * @throws NoSuchFileException
3471N/A * if the file does not exist <i>(optional specific exception)</i>
3471N/A * @throws DirectoryNotEmptyException
3471N/A * if the file is a directory and could not otherwise be deleted
3471N/A * because the directory is not empty <i>(optional specific
3471N/A * exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkDelete(String)} method
3471N/A * is invoked to check delete access to the file
3471N/A */
3471N/A public static void delete(Path path) throws IOException {
3471N/A provider(path).delete(path);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Deletes a file if it exists.
3471N/A *
3471N/A * <p> As with the {@link #delete(Path) delete(Path)} method, an
3471N/A * implementation may need to examine the file to determine if the file is a
3471N/A * directory. Consequently this method may not be atomic with respect to
3471N/A * other file system operations. If the file is a symbolic link, then the
3471N/A * symbolic link itself, not the final target of the link, is deleted.
3471N/A *
3471N/A * <p> If the file is a directory then the directory must be empty. In some
3471N/A * implementations a directory has entries for special files or links that
3471N/A * are created when the directory is created. In such implementations a
3471N/A * directory is considered empty when only the special entries exist.
3471N/A *
3471N/A * <p> On some operating systems it may not be possible to remove a file when
3471N/A * it is open and in use by this Java virtual machine or other programs.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to delete
3471N/A *
3471N/A * @return {@code true} if the file was deleted by this method; {@code
3471N/A * false} if the file could not be deleted because it did not
3471N/A * exist
3471N/A *
3471N/A * @throws DirectoryNotEmptyException
3471N/A * if the file is a directory and could not otherwise be deleted
3471N/A * because the directory is not empty <i>(optional specific
3471N/A * exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkDelete(String)} method
3471N/A * is invoked to check delete access to the file.
3471N/A */
3471N/A public static boolean deleteIfExists(Path path) throws IOException {
3471N/A return provider(path).deleteIfExists(path);
3471N/A }
3471N/A
3471N/A // -- Copying and moving files --
3471N/A
3471N/A /**
3471N/A * Copy a file to a target file.
3471N/A *
3471N/A * <p> This method copies a file to the target file with the {@code
3471N/A * options} parameter specifying how the copy is performed. By default, the
3471N/A * copy fails if the target file already exists or is a symbolic link,
3471N/A * except if the source and target are the {@link #isSameFile same} file, in
3471N/A * which case the method completes without copying the file. File attributes
3471N/A * are not required to be copied to the target file. If symbolic links are
3471N/A * supported, and the file is a symbolic link, then the final target of the
3471N/A * link is copied. If the file is a directory then it creates an empty
3471N/A * directory in the target location (entries in the directory are not
3471N/A * copied). This method can be used with the {@link #walkFileTree
3471N/A * walkFileTree} method to copy a directory and all entries in the directory,
3471N/A * or an entire <i>file-tree</i> where required.
3471N/A *
3471N/A * <p> The {@code options} parameter may include any of the following:
3471N/A *
3471N/A * <table border=1 cellpadding=5 summary="">
3471N/A * <tr> <th>Option</th> <th>Description</th> </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td>
3471N/A * <td> If the target file exists, then the target file is replaced if it
3471N/A * is not a non-empty directory. If the target file exists and is a
3471N/A * symbolic link, then the symbolic link itself, not the target of
3471N/A * the link, is replaced. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </td>
3471N/A * <td> Attempts to copy the file attributes associated with this file to
3471N/A * the target file. The exact file attributes that are copied is platform
3471N/A * and file system dependent and therefore unspecified. Minimally, the
3471N/A * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is
3471N/A * copied to the target file if supported by both the source and target
3471N/A * file store. Copying of file timestamps may result in precision
3471N/A * loss. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </td>
3471N/A * <td> Symbolic links are not followed. If the file is a symbolic link,
3471N/A * then the symbolic link itself, not the target of the link, is copied.
3471N/A * It is implementation specific if file attributes can be copied to the
3471N/A * new link. In other words, the {@code COPY_ATTRIBUTES} option may be
3471N/A * ignored when copying a symbolic link. </td>
3471N/A * </tr>
3471N/A * </table>
3471N/A *
3471N/A * <p> An implementation of this interface may support additional
3471N/A * implementation specific options.
3471N/A *
3471N/A * <p> Copying a file is not an atomic operation. If an {@link IOException}
3471N/A * is thrown then it possible that the target file is incomplete or some of
3471N/A * its file attributes have not been copied from the source file. When the
3471N/A * {@code REPLACE_EXISTING} option is specified and the target file exists,
3471N/A * then the target file is replaced. The check for the existence of the file
3471N/A * and the creation of the new file may not be atomic with respect to other
3471N/A * file system activities.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to copy a file into a directory, giving it the same file
3471N/A * name as the source file:
3471N/A * <pre>
3471N/A * Path source = ...
3471N/A * Path newdir = ...
3471N/A * Files.copy(source, newdir.resolve(source.getFileName());
3471N/A * </pre>
3471N/A *
3471N/A * @param source
3471N/A * the path to the file to copy
3471N/A * @param target
3471N/A * the path to the target file (may be associated with a different
3471N/A * provider to the source path)
3471N/A * @param options
3471N/A * options specifying how the copy should be done
3471N/A *
3471N/A * @return the path to the target file
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains a copy option that is not supported
3471N/A * @throws FileAlreadyExistsException
3471N/A * if the target file exists but cannot be replaced because the
3471N/A * {@code REPLACE_EXISTING} option is not specified <i>(optional
3471N/A * specific exception)</i>
3471N/A * @throws DirectoryNotEmptyException
3471N/A * the {@code REPLACE_EXISTING} option is specified but the file
3471N/A * cannot be replaced because it is a non-empty directory
3471N/A * <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the source file, the
3471N/A * {@link SecurityManager#checkWrite(String) checkWrite} is invoked
3471N/A * to check write access to the target file. If a symbolic link is
3471N/A * copied the security manager is invoked to check {@link
3471N/A * LinkPermission}{@code ("symbolic")}.
3471N/A */
3471N/A public static Path copy(Path source, Path target, CopyOption... options)
3471N/A throws IOException
3471N/A {
3471N/A FileSystemProvider provider = provider(source);
3471N/A if (provider(target) == provider) {
3471N/A // same provider
3471N/A provider.copy(source, target, options);
3471N/A } else {
3471N/A // different providers
3471N/A CopyMoveHelper.copyToForeignTarget(source, target, options);
3471N/A }
3471N/A return target;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Move or rename a file to a target file.
3471N/A *
3471N/A * <p> By default, this method attempts to move the file to the target
3471N/A * file, failing if the target file exists except if the source and
3471N/A * target are the {@link #isSameFile same} file, in which case this method
3471N/A * has no effect. If the file is a symbolic link then the symbolic link
3471N/A * itself, not the target of the link, is moved. This method may be
3471N/A * invoked to move an empty directory. In some implementations a directory
3471N/A * has entries for special files or links that are created when the
3471N/A * directory is created. In such implementations a directory is considered
3471N/A * empty when only the special entries exist. When invoked to move a
3471N/A * directory that is not empty then the directory is moved if it does not
3471N/A * require moving the entries in the directory. For example, renaming a
3471N/A * directory on the same {@link FileStore} will usually not require moving
3471N/A * the entries in the directory. When moving a directory requires that its
3471N/A * entries be moved then this method fails (by throwing an {@code
3471N/A * IOException}). To move a <i>file tree</i> may involve copying rather
3471N/A * than moving directories and this can be done using the {@link
3471N/A * #copy copy} method in conjunction with the {@link
3471N/A * #walkFileTree Files.walkFileTree} utility method.
3471N/A *
3471N/A * <p> The {@code options} parameter may include any of the following:
3471N/A *
3471N/A * <table border=1 cellpadding=5 summary="">
3471N/A * <tr> <th>Option</th> <th>Description</th> </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td>
3471N/A * <td> If the target file exists, then the target file is replaced if it
3471N/A * is not a non-empty directory. If the target file exists and is a
3471N/A * symbolic link, then the symbolic link itself, not the target of
3471N/A * the link, is replaced. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </td>
3471N/A * <td> The move is performed as an atomic file system operation and all
3471N/A * other options are ignored. If the target file exists then it is
3471N/A * implementation specific if the existing file is replaced or this method
3471N/A * fails by throwing an {@link IOException}. If the move cannot be
3471N/A * performed as an atomic file system operation then {@link
3471N/A * AtomicMoveNotSupportedException} is thrown. This can arise, for
3471N/A * example, when the target location is on a different {@code FileStore}
3471N/A * and would require that the file be copied, or target location is
3471N/A * associated with a different provider to this object. </td>
3471N/A * </table>
3471N/A *
3471N/A * <p> An implementation of this interface may support additional
3471N/A * implementation specific options.
3471N/A *
3471N/A * <p> Where the move requires that the file be copied then the {@link
3471N/A * BasicFileAttributes#lastModifiedTime last-modified-time} is copied to the
3471N/A * new file. An implementation may also attempt to copy other file
3471N/A * attributes but is not required to fail if the file attributes cannot be
3471N/A * copied. When the move is performed as a non-atomic operation, and a {@code
3471N/A * IOException} is thrown, then the state of the files is not defined. The
3471N/A * original file and the target file may both exist, the target file may be
3471N/A * incomplete or some of its file attributes may not been copied from the
3471N/A * original file.
3471N/A *
3471N/A * <p> <b>Usage Examples:</b>
3471N/A * Suppose we want to rename a file to "newname", keeping the file in the
3471N/A * same directory:
3471N/A * <pre>
3471N/A * Path source = ...
3471N/A * Files.move(source, source.resolveSibling("newname"));
3471N/A * </pre>
3471N/A * Alternatively, suppose we want to move a file to new directory, keeping
3471N/A * the same file name, and replacing any existing file of that name in the
3471N/A * directory:
3471N/A * <pre>
3471N/A * Path source = ...
3471N/A * Path newdir = ...
3471N/A * Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
3471N/A * </pre>
3471N/A *
3471N/A * @param source
3471N/A * the path to the file to move
3471N/A * @param target
3471N/A * the path to the target file (may be associated with a different
3471N/A * provider to the source path)
3471N/A * @param options
3471N/A * options specifying how the move should be done
3471N/A *
3471N/A * @return the path to the target file
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the array contains a copy option that is not supported
3471N/A * @throws FileAlreadyExistsException
3471N/A * if the target file exists but cannot be replaced because the
3471N/A * {@code REPLACE_EXISTING} option is not specified <i>(optional
3471N/A * specific exception)</i>
3471N/A * @throws DirectoryNotEmptyException
3471N/A * the {@code REPLACE_EXISTING} option is specified but the file
3471N/A * cannot be replaced because it is a non-empty directory
3471N/A * <i>(optional specific exception)</i>
3471N/A * @throws AtomicMoveNotSupportedException
3471N/A * if the options array contains the {@code ATOMIC_MOVE} option but
3471N/A * the file cannot be moved as an atomic file system operation.
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to both the source and
3471N/A * target file.
3471N/A */
3471N/A public static Path move(Path source, Path target, CopyOption... options)
3471N/A throws IOException
3471N/A {
3471N/A FileSystemProvider provider = provider(source);
3471N/A if (provider(target) == provider) {
3471N/A // same provider
3471N/A provider.move(source, target, options);
3471N/A } else {
3471N/A // different providers
3471N/A CopyMoveHelper.moveToForeignTarget(source, target, options);
3471N/A }
3471N/A return target;
3471N/A }
3471N/A
3471N/A // -- Miscellenous --
3471N/A
3471N/A /**
3471N/A * Reads the target of a symbolic link <i>(optional operation)</i>.
3471N/A *
3471N/A * <p> If the file system supports <a href="package-summary.html#links">symbolic
3471N/A * links</a> then this method is used to read the target of the link, failing
3471N/A * if the file is not a symbolic link. The target of the link need not exist.
3471N/A * The returned {@code Path} object will be associated with the same file
3471N/A * system as {@code link}.
3471N/A *
3471N/A * @param link
3471N/A * the path to the symbolic link
3471N/A *
3471N/A * @return a {@code Path} object representing the target of the link
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the implementation does not support symbolic links
3471N/A * @throws NotLinkException
3471N/A * if the target could otherwise not be read because the file
3471N/A * is not a symbolic link <i>(optional specific exception)</i>
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager
3471N/A * is installed, it checks that {@code FilePermission} has been
3471N/A * granted with the "{@code readlink}" action to read the link.
3471N/A */
3471N/A public static Path readSymbolicLink(Path link) throws IOException {
3471N/A return provider(link).readSymbolicLink(link);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Returns the {@link FileStore} representing the file store where a file
3471N/A * is located.
3471N/A *
3471N/A * <p> Once a reference to the {@code FileStore} is obtained it is
3471N/A * implementation specific if operations on the returned {@code FileStore},
3471N/A * or {@link FileStoreAttributeView} objects obtained from it, continue
3471N/A * to depend on the existence of the file. In particular the behavior is not
3471N/A * defined for the case that the file is deleted or moved to a different
3471N/A * file store.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A *
3471N/A * @return the file store where the file is stored
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file, and in
3471N/A * addition it checks {@link RuntimePermission}<tt>
3471N/A * ("getFileStoreAttributes")</tt>
3471N/A */
3471N/A public static FileStore getFileStore(Path path) throws IOException {
3471N/A return provider(path).getFileStore(path);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests if two paths locate the same file.
3471N/A *
3471N/A * <p> If both {@code Path} objects are {@link Path#equals(Object) equal}
3471N/A * then this method returns {@code true} without checking if the file exists.
3471N/A * If the two {@code Path} objects are associated with different providers
3471N/A * then this method returns {@code false}. Otherwise, this method checks if
3471N/A * both {@code Path} objects locate the same file, and depending on the
3471N/A * implementation, may require to open or access both files.
3471N/A *
3471N/A * <p> If the file system and files remain static, then this method implements
3471N/A * an equivalence relation for non-null {@code Paths}.
3471N/A * <ul>
3471N/A * <li>It is <i>reflexive</i>: for {@code Path} {@code f},
3471N/A * {@code isSameFile(f,f)} should return {@code true}.
3471N/A * <li>It is <i>symmetric</i>: for two {@code Paths} {@code f} and {@code g},
3471N/A * {@code isSameFile(f,g)} will equal {@code isSameFile(g,f)}.
3471N/A * <li>It is <i>transitive</i>: for three {@code Paths}
3471N/A * {@code f}, {@code g}, and {@code h}, if {@code isSameFile(f,g)} returns
3471N/A * {@code true} and {@code isSameFile(g,h)} returns {@code true}, then
3471N/A * {@code isSameFile(g,h)} will return return {@code true}.
3471N/A * </ul>
3471N/A *
3471N/A * @param path
3471N/A * one path to the file
3471N/A * @param path2
3471N/A * the other path
3471N/A *
3471N/A * @return {@code true} if, and only if, the two paths locate the same file
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to both files.
3471N/A *
3471N/A * @see java.nio.file.attribute.BasicFileAttributes#fileKey
3471N/A */
3471N/A public static boolean isSameFile(Path path, Path path2) throws IOException {
3471N/A return provider(path).isSameFile(path, path2);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tells whether or not a file is considered <em>hidden</em>. The exact
3471N/A * definition of hidden is platform or provider dependent. On UNIX for
3471N/A * example a file is considered to be hidden if its name begins with a
3471N/A * period character ('.'). On Windows a file is considered hidden if it
3471N/A * isn't a directory and the DOS {@link DosFileAttributes#isHidden hidden}
3471N/A * attribute is set.
3471N/A *
3471N/A * <p> Depending on the implementation this method may require to access
3471N/A * the file system to determine if the file is considered hidden.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to test
3471N/A *
3471N/A * @return {@code true} if the file is considered hidden
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
3471N/A */
3471N/A public static boolean isHidden(Path path) throws IOException {
3471N/A return provider(path).isHidden(path);
3471N/A }
3471N/A
893N/A // lazy loading of default and installed file type detectors
3471N/A private static class FileTypeDetectors{
893N/A static final FileTypeDetector defaultFileTypeDetector =
6252N/A createDefaultFileTypeDetector();
893N/A static final List<FileTypeDetector> installeDetectors =
893N/A loadInstalledDetectors();
893N/A
6252N/A // creates the default file type detector
6252N/A private static FileTypeDetector createDefaultFileTypeDetector() {
6252N/A return AccessController
6252N/A .doPrivileged(new PrivilegedAction<FileTypeDetector>() {
6252N/A @Override public FileTypeDetector run() {
6252N/A return sun.nio.fs.DefaultFileTypeDetector.create();
6252N/A }});
6252N/A }
6252N/A
893N/A // loads all installed file type detectors
893N/A private static List<FileTypeDetector> loadInstalledDetectors() {
893N/A return AccessController
893N/A .doPrivileged(new PrivilegedAction<List<FileTypeDetector>>() {
893N/A @Override public List<FileTypeDetector> run() {
3471N/A List<FileTypeDetector> list = new ArrayList<>();
893N/A ServiceLoader<FileTypeDetector> loader = ServiceLoader
893N/A .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader());
893N/A for (FileTypeDetector detector: loader) {
893N/A list.add(detector);
893N/A }
893N/A return list;
893N/A }});
893N/A }
893N/A }
893N/A
893N/A /**
893N/A * Probes the content type of a file.
893N/A *
893N/A * <p> This method uses the installed {@link FileTypeDetector} implementations
893N/A * to probe the given file to determine its content type. Each file type
893N/A * detector's {@link FileTypeDetector#probeContentType probeContentType} is
893N/A * invoked, in turn, to probe the file type. If the file is recognized then
893N/A * the content type is returned. If the file is not recognized by any of the
893N/A * installed file type detectors then a system-default file type detector is
893N/A * invoked to guess the content type.
893N/A *
893N/A * <p> A given invocation of the Java virtual machine maintains a system-wide
893N/A * list of file type detectors. Installed file type detectors are loaded
893N/A * using the service-provider loading facility defined by the {@link ServiceLoader}
893N/A * class. Installed file type detectors are loaded using the system class
893N/A * loader. If the system class loader cannot be found then the extension class
893N/A * loader is used; If the extension class loader cannot be found then the
893N/A * bootstrap class loader is used. File type detectors are typically installed
893N/A * by placing them in a JAR file on the application class path or in the
893N/A * extension directory, the JAR file contains a provider-configuration file
893N/A * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory
893N/A * {@code META-INF/services}, and the file lists one or more fully-qualified
893N/A * names of concrete subclass of {@code FileTypeDetector } that have a zero
893N/A * argument constructor. If the process of locating or instantiating the
893N/A * installed file type detectors fails then an unspecified error is thrown.
893N/A * The ordering that installed providers are located is implementation
893N/A * specific.
893N/A *
893N/A * <p> The return value of this method is the string form of the value of a
893N/A * Multipurpose Internet Mail Extension (MIME) content type as
893N/A * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC&nbsp;2045:
893N/A * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet
893N/A * Message Bodies</i></a>. The string is guaranteed to be parsable according
893N/A * to the grammar in the RFC.
893N/A *
3471N/A * @param path
3471N/A * the path to the file to probe
893N/A *
893N/A * @return The content type of the file, or {@code null} if the content
893N/A * type cannot be determined
893N/A *
893N/A * @throws IOException
3471N/A * if an I/O error occurs
893N/A * @throws SecurityException
893N/A * If a security manager is installed and it denies an unspecified
893N/A * permission required by a file type detector implementation.
893N/A */
3471N/A public static String probeContentType(Path path)
893N/A throws IOException
893N/A {
893N/A // try installed file type detectors
3471N/A for (FileTypeDetector detector: FileTypeDetectors.installeDetectors) {
3471N/A String result = detector.probeContentType(path);
893N/A if (result != null)
893N/A return result;
893N/A }
893N/A
893N/A // fallback to default
3471N/A return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path);
3471N/A }
3471N/A
3471N/A // -- File Attributes --
3471N/A
3471N/A /**
3471N/A * Returns a file attribute view of a given type.
3471N/A *
3471N/A * <p> A file attribute view provides a read-only or updatable view of a
3471N/A * set of file attributes. This method is intended to be used where the file
3471N/A * attribute view defines type-safe methods to read or update the file
3471N/A * attributes. The {@code type} parameter is the type of the attribute view
3471N/A * required and the method returns an instance of that type if supported.
3471N/A * The {@link BasicFileAttributeView} type supports access to the basic
3471N/A * attributes of a file. Invoking this method to select a file attribute
3471N/A * view of that type will always return an instance of that class.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled by the resulting file attribute view for the case that the
3471N/A * file is a symbolic link. By default, symbolic links are followed. If the
3471N/A * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then
3471N/A * symbolic links are not followed. This option is ignored by implementations
3471N/A * that do not support symbolic links.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want read or set a file's ACL, if supported:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
3471N/A * if (view != null) {
3471N/A * List&lt;AclEntry&gt acl = view.getAcl();
3471N/A * :
3471N/A * }
3471N/A * </pre>
3471N/A *
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param type
3471N/A * the {@code Class} object corresponding to the file attribute view
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return a file attribute view of the specified type, or {@code null} if
3471N/A * the attribute view type is not available
3471N/A */
3471N/A public static <V extends FileAttributeView> V getFileAttributeView(Path path,
3471N/A Class<V> type,
3471N/A LinkOption... options)
3471N/A {
3471N/A return provider(path).getFileAttributeView(path, type, options);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Reads a file's attributes as a bulk operation.
3471N/A *
3471N/A * <p> The {@code type} parameter is the type of the attributes required
3471N/A * and this method returns an instance of that type if supported. All
3471N/A * implementations support a basic set of file attributes and so invoking
3471N/A * this method with a {@code type} parameter of {@code
3471N/A * BasicFileAttributes.class} will not throw {@code
3471N/A * UnsupportedOperationException}.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> It is implementation specific if all file attributes are read as an
3471N/A * atomic operation with respect to other file system operations.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to read a file's attributes in bulk:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
3471N/A * </pre>
3471N/A * Alternatively, suppose we want to read file's POSIX attributes without
3471N/A * following symbolic links:
3471N/A * <pre>
3471N/A * PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param type
3471N/A * the {@code Class} of the file attributes required
3471N/A * to read
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return the file attributes
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if an attributes of the given type are not supported
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file. If this
3471N/A * method is invoked to read security sensitive attributes then the
3471N/A * security manager may be invoke to check for additional permissions.
3471N/A */
3471N/A public static <A extends BasicFileAttributes> A readAttributes(Path path,
3471N/A Class<A> type,
3471N/A LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return provider(path).readAttributes(path, type, options);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Sets the value of a file attribute.
3471N/A *
3471N/A * <p> The {@code attribute} parameter identifies the attribute to be set
3471N/A * and takes the form:
3471N/A * <blockquote>
3471N/A * [<i>view-name</i><b>:</b>]<i>attribute-name</i>
3471N/A * </blockquote>
3471N/A * where square brackets [...] delineate an optional component and the
3471N/A * character {@code ':'} stands for itself.
3471N/A *
3471N/A * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link
3471N/A * FileAttributeView} that identifies a set of file attributes. If not
3471N/A * specified then it defaults to {@code "basic"}, the name of the file
3471N/A * attribute view that identifies the basic set of file attributes common to
3471N/A * many file systems. <i>attribute-name</i> is the name of the attribute
3471N/A * within the set.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to set the DOS "hidden" attribute:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * Files.setAttribute(path, "dos:hidden", true);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param attribute
3471N/A * the attribute to set
3471N/A * @param value
3471N/A * the attribute value
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return the {@code path} parameter
3471N/A *
3471N/A * @throws UnsupportedOperationException
3779N/A * if the attribute view is not available
3471N/A * @throws IllegalArgumentException
3779N/A * if the attribute name is not specified, or is not recognized, or
3779N/A * the attribute value is of the correct type but has an
3471N/A * inappropriate value
3471N/A * @throws ClassCastException
3471N/A * if the attribute value is not of the expected type or is a
3471N/A * collection containing elements that are not of the expected
3471N/A * type
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method denies write access to the file. If this method is invoked
3471N/A * to set security sensitive attributes then the security manager
3471N/A * may be invoked to check for additional permissions.
3471N/A */
3471N/A public static Path setAttribute(Path path, String attribute, Object value,
3471N/A LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A provider(path).setAttribute(path, attribute, value, options);
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Reads the value of a file attribute.
3471N/A *
3471N/A * <p> The {@code attribute} parameter identifies the attribute to be read
3471N/A * and takes the form:
3471N/A * <blockquote>
3471N/A * [<i>view-name</i><b>:</b>]<i>attribute-name</i>
3471N/A * </blockquote>
3471N/A * where square brackets [...] delineate an optional component and the
3471N/A * character {@code ':'} stands for itself.
3471N/A *
3471N/A * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link
3471N/A * FileAttributeView} that identifies a set of file attributes. If not
3471N/A * specified then it defaults to {@code "basic"}, the name of the file
3471N/A * attribute view that identifies the basic set of file attributes common to
3471N/A * many file systems. <i>attribute-name</i> is the name of the attribute.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we require the user ID of the file owner on a system that
3471N/A * supports a "{@code unix}" view:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * int uid = (Integer)Files.getAttribute(path, "unix:uid");
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param attribute
3471N/A * the attribute to read
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3779N/A * @return the attribute value
3471N/A *
3779N/A * @throws UnsupportedOperationException
3779N/A * if the attribute view is not available
3779N/A * @throws IllegalArgumentException
3779N/A * if the attribute name is not specified or is not recognized
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file. If this method is invoked
3471N/A * to read security sensitive attributes then the security manager
3471N/A * may be invoked to check for additional permissions.
3471N/A */
3471N/A public static Object getAttribute(Path path, String attribute,
3471N/A LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A // only one attribute should be read
3471N/A if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0)
3779N/A throw new IllegalArgumentException(attribute);
3471N/A Map<String,Object> map = readAttributes(path, attribute, options);
3779N/A assert map.size() == 1;
3471N/A String name;
3471N/A int pos = attribute.indexOf(':');
3471N/A if (pos == -1) {
3471N/A name = attribute;
3471N/A } else {
3471N/A name = (pos == attribute.length()) ? "" : attribute.substring(pos+1);
3471N/A }
3471N/A return map.get(name);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Reads a set of file attributes as a bulk operation.
3471N/A *
3471N/A * <p> The {@code attributes} parameter identifies the attributes to be read
3471N/A * and takes the form:
3471N/A * <blockquote>
3471N/A * [<i>view-name</i><b>:</b>]<i>attribute-list</i>
3471N/A * </blockquote>
3471N/A * where square brackets [...] delineate an optional component and the
3471N/A * character {@code ':'} stands for itself.
3471N/A *
3471N/A * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link
3471N/A * FileAttributeView} that identifies a set of file attributes. If not
3471N/A * specified then it defaults to {@code "basic"}, the name of the file
3471N/A * attribute view that identifies the basic set of file attributes common to
3471N/A * many file systems.
3471N/A *
3471N/A * <p> The <i>attribute-list</i> component is a comma separated list of
3471N/A * zero or more names of attributes to read. If the list contains the value
3471N/A * {@code "*"} then all attributes are read. Attributes that are not supported
3471N/A * are ignored and will not be present in the returned map. It is
3471N/A * implementation specific if all attributes are read as an atomic operation
3471N/A * with respect to other file system operations.
3471N/A *
3471N/A * <p> The following examples demonstrate possible values for the {@code
3471N/A * attributes} parameter:
3471N/A *
3471N/A * <blockquote>
3471N/A * <table border="0">
3471N/A * <tr>
3471N/A * <td> {@code "*"} </td>
3471N/A * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@code "size,lastModifiedTime,lastAccessTime"} </td>
3471N/A * <td> Reads the file size, last modified time, and last access time
3471N/A * attributes. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@code "posix:*"} </td>
3471N/A * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td>
3471N/A * </tr>
3471N/A * <tr>
3471N/A * <td> {@code "posix:permissions,owner,size"} </td>
3471N/A * <td> Reads the POSX file permissions, owner, and file size. </td>
3471N/A * </tr>
3471N/A * </table>
3471N/A * </blockquote>
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param attributes
3471N/A * the attributes to read
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3779N/A * @return a map of the attributes returned; The map's keys are the
3779N/A * attribute names, its values are the attribute values
3471N/A *
3779N/A * @throws UnsupportedOperationException
3779N/A * if the attribute view is not available
3779N/A * @throws IllegalArgumentException
3779N/A * if no attributes are specified or an unrecognized attributes is
3779N/A * specified
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file. If this method is invoked
3471N/A * to read security sensitive attributes then the security manager
3471N/A * may be invoke to check for additional permissions.
3471N/A */
3471N/A public static Map<String,Object> readAttributes(Path path, String attributes,
3471N/A LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return provider(path).readAttributes(path, attributes, options);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Returns a file's POSIX file permissions.
3471N/A *
3471N/A * <p> The {@code path} parameter is associated with a {@code FileSystem}
3471N/A * that supports the {@link PosixFileAttributeView}. This attribute view
3471N/A * provides access to file attributes commonly associated with files on file
3471N/A * systems used by operating systems that implement the Portable Operating
3471N/A * System Interface (POSIX) family of standards.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return the file permissions
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the associated file system does not support the {@code
3471N/A * PosixFileAttributeView}
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, a security manager is
3471N/A * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
3471N/A * or its {@link SecurityManager#checkRead(String) checkRead} method
3471N/A * denies read access to the file.
3471N/A */
3471N/A public static Set<PosixFilePermission> getPosixFilePermissions(Path path,
3471N/A LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return readAttributes(path, PosixFileAttributes.class, options).permissions();
3471N/A }
3471N/A
3471N/A /**
3471N/A * Sets a file's POSIX permissions.
3471N/A *
3471N/A * <p> The {@code path} parameter is associated with a {@code FileSystem}
3471N/A * that supports the {@link PosixFileAttributeView}. This attribute view
3471N/A * provides access to file attributes commonly associated with files on file
3471N/A * systems used by operating systems that implement the Portable Operating
3471N/A * System Interface (POSIX) family of standards.
3471N/A *
3471N/A * @param path
3471N/A * A file reference that locates the file
3471N/A * @param perms
3471N/A * The new set of permissions
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the associated file system does not support the {@code
3471N/A * PosixFileAttributeView}
3471N/A * @throws ClassCastException
3471N/A * if the sets contains elements that are not of type {@code
3471N/A * PosixFilePermission}
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
3471N/A * or its {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method denies write access to the file.
3471N/A */
3471N/A public static Path setPosixFilePermissions(Path path,
3471N/A Set<PosixFilePermission> perms)
3471N/A throws IOException
3471N/A {
3471N/A PosixFileAttributeView view =
3471N/A getFileAttributeView(path, PosixFileAttributeView.class);
3471N/A if (view == null)
3471N/A throw new UnsupportedOperationException();
3471N/A view.setPermissions(perms);
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Returns the owner of a file.
3471N/A *
3471N/A * <p> The {@code path} parameter is associated with a file system that
3471N/A * supports {@link FileOwnerAttributeView}. This file attribute view provides
3471N/A * access to a file attribute that is the owner of the file.
3471N/A *
3471N/A * @param path
3471N/A * A file reference that locates the file
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return A user principal representing the owner of the file
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the associated file system does not support the {@code
3471N/A * FileOwnerAttributeView}
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
3471N/A * or its {@link SecurityManager#checkRead(String) checkRead} method
3471N/A * denies read access to the file.
3471N/A */
3471N/A public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException {
3471N/A FileOwnerAttributeView view =
3471N/A getFileAttributeView(path, FileOwnerAttributeView.class, options);
3471N/A if (view == null)
3471N/A throw new UnsupportedOperationException();
3471N/A return view.getOwner();
893N/A }
893N/A
893N/A /**
3471N/A * Updates the file owner.
3471N/A *
3471N/A * <p> The {@code path} parameter is associated with a file system that
3471N/A * supports {@link FileOwnerAttributeView}. This file attribute view provides
3471N/A * access to a file attribute that is the owner of the file.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to make "joe" the owner of a file:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * UserPrincipalLookupService lookupService =
3471N/A * provider(path).getUserPrincipalLookupService();
3471N/A * UserPrincipal joe = lookupService.lookupPrincipalByName("joe");
3471N/A * Files.setOwner(path, joe);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * A file reference that locates the file
3471N/A * @param owner
3471N/A * The new file owner
3471N/A *
3471N/A * @throws UnsupportedOperationException
3471N/A * if the associated file system does not support the {@code
3471N/A * FileOwnerAttributeView}
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
3471N/A * or its {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method denies write access to the file.
3471N/A *
3471N/A * @see FileSystem#getUserPrincipalLookupService
3471N/A * @see java.nio.file.attribute.UserPrincipalLookupService
3471N/A */
3471N/A public static Path setOwner(Path path, UserPrincipal owner)
3471N/A throws IOException
3471N/A {
3471N/A FileOwnerAttributeView view =
3471N/A getFileAttributeView(path, FileOwnerAttributeView.class);
3471N/A if (view == null)
3471N/A throw new UnsupportedOperationException();
3471N/A view.setOwner(owner);
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is a symbolic link.
3471N/A *
3471N/A * <p> Where is it required to distinguish an I/O exception from the case
3471N/A * that the file is not a symbolic link then the file attributes can be
3471N/A * read with the {@link #readAttributes(Path,Class,LinkOption[])
3471N/A * readAttributes} method and the file type tested with the {@link
3471N/A * BasicFileAttributes#isSymbolicLink} method.
3471N/A *
3471N/A * @return {@code true} if the file is a symbolic link; {@code false} if
3471N/A * the file does not exist, is not a symbolic link, or it cannot
3900N/A * be determined if the file is a symbolic link or not.
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file.
3471N/A */
3471N/A public static boolean isSymbolicLink(Path path) {
3471N/A try {
3471N/A return readAttributes(path,
3471N/A BasicFileAttributes.class,
3471N/A LinkOption.NOFOLLOW_LINKS).isSymbolicLink();
3471N/A } catch (IOException ioe) {
3471N/A return false;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is a directory.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> Where is it required to distinguish an I/O exception from the case
3471N/A * that the file is not a directory then the file attributes can be
3471N/A * read with the {@link #readAttributes(Path,Class,LinkOption[])
3471N/A * readAttributes} method and the file type tested with the {@link
3471N/A * BasicFileAttributes#isDirectory} method.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to test
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return {@code true} if the file is a directory; {@code false} if
3471N/A * the file does not exist, is not a directory, or it cannot
3900N/A * be determined if the file is a directory or not.
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file.
3471N/A */
3471N/A public static boolean isDirectory(Path path, LinkOption... options) {
3471N/A try {
3471N/A return readAttributes(path, BasicFileAttributes.class, options).isDirectory();
3471N/A } catch (IOException ioe) {
3471N/A return false;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is a regular file with opaque content.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> Where is it required to distinguish an I/O exception from the case
3471N/A * that the file is not a regular file then the file attributes can be
3471N/A * read with the {@link #readAttributes(Path,Class,LinkOption[])
3471N/A * readAttributes} method and the file type tested with the {@link
3471N/A * BasicFileAttributes#isRegularFile} method.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return {@code true} if the file is a regular file; {@code false} if
3900N/A * the file does not exist, is not a regular file, or it
3900N/A * cannot be determined if the file is a regular file or not.
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file.
3471N/A */
3471N/A public static boolean isRegularFile(Path path, LinkOption... options) {
3471N/A try {
3471N/A return readAttributes(path, BasicFileAttributes.class, options).isRegularFile();
3471N/A } catch (IOException ioe) {
3471N/A return false;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Returns a file's last modified time.
3471N/A *
3471N/A * <p> The {@code options} array may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed and the file attribute of the final target
3471N/A * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return a {@code FileTime} representing the time the file was last
3471N/A * modified, or an implementation specific default when a time
3471N/A * stamp to indicate the time of last modification is not supported
3471N/A * by the file system
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file.
3471N/A *
3471N/A * @see BasicFileAttributes#lastModifiedTime
3471N/A */
3471N/A public static FileTime getLastModifiedTime(Path path, LinkOption... options)
3471N/A throws IOException
3471N/A {
3471N/A return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime();
3471N/A }
3471N/A
3471N/A /**
3471N/A * Updates a file's last modified time attribute. The file time is converted
3471N/A * to the epoch and precision supported by the file system. Converting from
3471N/A * finer to coarser granularities result in precision loss. The behavior of
3471N/A * this method when attempting to set the last modified time when it is not
3471N/A * supported by the file system or is outside the range supported by the
3471N/A * underlying file store is not defined. It may or not fail by throwing an
3471N/A * {@code IOException}.
3471N/A *
3471N/A * <p> <b>Usage Example:</b>
3471N/A * Suppose we want to set the last modified time to the current time:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * FileTime now = FileTime.fromMillis(System.currentTimeMillis());
3471N/A * Files.setLastModifiedTime(path, now);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param time
3471N/A * the new last modified time
3471N/A *
3471N/A * @return the file
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, the security manager's {@link
3471N/A * SecurityManager#checkWrite(String) checkWrite} method is invoked
3471N/A * to check write access to file
3471N/A *
3471N/A * @see BasicFileAttributeView#setTimes
3471N/A */
3471N/A public static Path setLastModifiedTime(Path path, FileTime time)
3471N/A throws IOException
3471N/A {
3471N/A getFileAttributeView(path, BasicFileAttributeView.class)
3471N/A .setTimes(time, null, null);
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Returns the size of a file (in bytes). The size may differ from the
3471N/A * actual size on the file system due to compression, support for sparse
3471N/A * files, or other reasons. The size of files that are not {@link
3471N/A * #isRegularFile regular} files is implementation specific and
3471N/A * therefore unspecified.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A *
3471N/A * @return the file size, in bytes
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, its {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method denies read access to the file.
3471N/A *
3471N/A * @see BasicFileAttributes#size
3471N/A */
3471N/A public static long size(Path path) throws IOException {
3471N/A return readAttributes(path, BasicFileAttributes.class).size();
3471N/A }
3471N/A
3471N/A // -- Accessibility --
3471N/A
3471N/A /**
3471N/A * Returns {@code false} if NOFOLLOW_LINKS is present.
3471N/A */
3471N/A private static boolean followLinks(LinkOption... options) {
3471N/A boolean followLinks = true;
3471N/A for (LinkOption opt: options) {
3471N/A if (opt == LinkOption.NOFOLLOW_LINKS) {
3471N/A followLinks = false;
3471N/A continue;
3471N/A }
3471N/A if (opt == null)
3471N/A throw new NullPointerException();
3471N/A throw new AssertionError("Should not get here");
3471N/A }
3471N/A return followLinks;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file exists.
3471N/A *
3471N/A * <p> The {@code options} parameter may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> Note that the result of this method is immediately outdated. If this
3471N/A * method indicates the file exists then there is no guarantee that a
3471N/A * subsequence access will succeed. Care should be taken when using this
3471N/A * method in security sensitive applications.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to test
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A * .
3471N/A * @return {@code true} if the file exists; {@code false} if the file does
3471N/A * not exist or its existence cannot be determined.
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, the {@link
3471N/A * SecurityManager#checkRead(String)} is invoked to check
3471N/A * read access to the file.
3471N/A *
3471N/A * @see #notExists
3471N/A */
3471N/A public static boolean exists(Path path, LinkOption... options) {
3471N/A try {
3471N/A if (followLinks(options)) {
3471N/A provider(path).checkAccess(path);
3471N/A } else {
3471N/A // attempt to read attributes without following links
3471N/A readAttributes(path, BasicFileAttributes.class,
3471N/A LinkOption.NOFOLLOW_LINKS);
3471N/A }
3471N/A // file exists
3471N/A return true;
3471N/A } catch (IOException x) {
3471N/A // does not exist or unable to determine if file exists
3471N/A return false;
3471N/A }
3471N/A
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether the file located by this path does not exist. This method
3471N/A * is intended for cases where it is required to take action when it can be
3471N/A * confirmed that a file does not exist.
3471N/A *
3471N/A * <p> The {@code options} parameter may be used to indicate how symbolic links
3471N/A * are handled for the case that the file is a symbolic link. By default,
3471N/A * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS
3471N/A * NOFOLLOW_LINKS} is present then symbolic links are not followed.
3471N/A *
3471N/A * <p> Note that this method is not the complement of the {@link #exists
3471N/A * exists} method. Where it is not possible to determine if a file exists
3471N/A * or not then both methods return {@code false}. As with the {@code exists}
3471N/A * method, the result of this method is immediately outdated. If this
3471N/A * method indicates the file does exist then there is no guarantee that a
3471N/A * subsequence attempt to create the file will succeed. Care should be taken
3471N/A * when using this method in security sensitive applications.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to test
3471N/A * @param options
3471N/A * options indicating how symbolic links are handled
3471N/A *
3471N/A * @return {@code true} if the file does not exist; {@code false} if the
3471N/A * file exists or its existence cannot be determined
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, the {@link
3471N/A * SecurityManager#checkRead(String)} is invoked to check
3471N/A * read access to the file.
3471N/A */
3471N/A public static boolean notExists(Path path, LinkOption... options) {
3471N/A try {
3471N/A if (followLinks(options)) {
3471N/A provider(path).checkAccess(path);
3471N/A } else {
3471N/A // attempt to read attributes without following links
3471N/A readAttributes(path, BasicFileAttributes.class,
3471N/A LinkOption.NOFOLLOW_LINKS);
3471N/A }
3471N/A // file exists
3471N/A return false;
3471N/A } catch (NoSuchFileException x) {
3471N/A // file confirmed not to exist
3471N/A return true;
3471N/A } catch (IOException x) {
3471N/A return false;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Used by isReadbale, isWritable, isExecutable to test access to a file.
3471N/A */
3471N/A private static boolean isAccessible(Path path, AccessMode... modes) {
3471N/A try {
3471N/A provider(path).checkAccess(path, modes);
3471N/A return true;
3471N/A } catch (IOException x) {
3471N/A return false;
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is readable. This method checks that a file exists
3471N/A * and that this Java virtual machine has appropriate privileges that would
3471N/A * allow it open the file for reading. Depending on the implementation, this
3471N/A * method may require to read file permissions, access control lists, or
3471N/A * other file attributes in order to check the effective access to the file.
3471N/A * Consequently, this method may not be atomic with respect to other file
3471N/A * system operations.
3471N/A *
3471N/A * <p> Note that the result of this method is immediately outdated, there is
3471N/A * no guarantee that a subsequent attempt to open the file for reading will
3471N/A * succeed (or even that it will access the same file). Care should be taken
3471N/A * when using this method in security sensitive applications.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to check
3471N/A *
3471N/A * @return {@code true} if the file exists and is readable; {@code false}
3471N/A * if the file does not exist, read access would be denied because
3471N/A * the Java virtual machine has insufficient privileges, or access
3471N/A * cannot be determined
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * is invoked to check read access to the file.
3471N/A */
3471N/A public static boolean isReadable(Path path) {
3471N/A return isAccessible(path, AccessMode.READ);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is writable. This method checks that a file exists
3471N/A * and that this Java virtual machine has appropriate privileges that would
3471N/A * allow it open the file for writing. Depending on the implementation, this
3471N/A * method may require to read file permissions, access control lists, or
3471N/A * other file attributes in order to check the effective access to the file.
3471N/A * Consequently, this method may not be atomic with respect to other file
3471N/A * system operations.
3471N/A *
3471N/A * <p> Note that result of this method is immediately outdated, there is no
3471N/A * guarantee that a subsequent attempt to open the file for writing will
3471N/A * succeed (or even that it will access the same file). Care should be taken
3471N/A * when using this method in security sensitive applications.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to check
3471N/A *
3471N/A * @return {@code true} if the file exists and is writable; {@code false}
3471N/A * if the file does not exist, write access would be denied because
3471N/A * the Java virtual machine has insufficient privileges, or access
3471N/A * cannot be determined
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * is invoked to check write access to the file.
3471N/A */
3471N/A public static boolean isWritable(Path path) {
3471N/A return isAccessible(path, AccessMode.WRITE);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Tests whether a file is executable. This method checks that a file exists
3471N/A * and that this Java virtual machine has appropriate privileges to {@link
3471N/A * Runtime#exec execute} the file. The semantics may differ when checking
3471N/A * access to a directory. For example, on UNIX systems, checking for
3471N/A * execute access checks that the Java virtual machine has permission to
3471N/A * search the directory in order to access file or subdirectories.
3471N/A *
3471N/A * <p> Depending on the implementation, this method may require to read file
3471N/A * permissions, access control lists, or other file attributes in order to
3471N/A * check the effective access to the file. Consequently, this method may not
3471N/A * be atomic with respect to other file system operations.
3471N/A *
3471N/A * <p> Note that the result of this method is immediately outdated, there is
3471N/A * no guarantee that a subsequent attempt to execute the file will succeed
3471N/A * (or even that it will access the same file). Care should be taken when
3471N/A * using this method in security sensitive applications.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file to check
3471N/A *
3471N/A * @return {@code true} if the file exists and is executable; {@code false}
3471N/A * if the file does not exist, execute access would be denied because
3471N/A * the Java virtual machine has insufficient privileges, or access
3471N/A * cannot be determined
3471N/A *
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkExec(String)
3471N/A * checkExec} is invoked to check execute access to the file.
3471N/A */
3471N/A public static boolean isExecutable(Path path) {
3471N/A return isAccessible(path, AccessMode.EXECUTE);
3471N/A }
3471N/A
3471N/A // -- Recursive operations --
3471N/A
3471N/A /**
893N/A * Walks a file tree.
893N/A *
893N/A * <p> This method walks a file tree rooted at a given starting file. The
893N/A * file tree traversal is <em>depth-first</em> with the given {@link
893N/A * FileVisitor} invoked for each file encountered. File tree traversal
1610N/A * completes when all accessible files in the tree have been visited, or a
1610N/A * visit method returns a result of {@link FileVisitResult#TERMINATE
2826N/A * TERMINATE}. Where a visit method terminates due an {@code IOException},
2826N/A * an uncaught error, or runtime exception, then the traversal is terminated
2826N/A * and the error or exception is propagated to the caller of this method.
893N/A *
3471N/A * <p> For each file encountered this method attempts to read its {@link
893N/A * java.nio.file.attribute.BasicFileAttributes}. If the file is not a
893N/A * directory then the {@link FileVisitor#visitFile visitFile} method is
893N/A * invoked with the file attributes. If the file attributes cannot be read,
893N/A * due to an I/O exception, then the {@link FileVisitor#visitFileFailed
893N/A * visitFileFailed} method is invoked with the I/O exception.
893N/A *
2826N/A * <p> Where the file is a directory, and the directory could not be opened,
2826N/A * then the {@code visitFileFailed} method is invoked with the I/O exception,
2826N/A * after which, the file tree walk continues, by default, at the next
2826N/A * <em>sibling</em> of the directory.
893N/A *
893N/A * <p> Where the directory is opened successfully, then the entries in the
893N/A * directory, and their <em>descendants</em> are visited. When all entries
893N/A * have been visited, or an I/O error occurs during iteration of the
893N/A * directory, then the directory is closed and the visitor's {@link
893N/A * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked.
893N/A * The file tree walk then continues, by default, at the next <em>sibling</em>
893N/A * of the directory.
893N/A *
893N/A * <p> By default, symbolic links are not automatically followed by this
893N/A * method. If the {@code options} parameter contains the {@link
893N/A * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are
893N/A * followed. When following links, and the attributes of the target cannot
893N/A * be read, then this method attempts to get the {@code BasicFileAttributes}
893N/A * of the link. If they can be read then the {@code visitFile} method is
893N/A * invoked with the attributes of the link (otherwise the {@code visitFileFailed}
893N/A * method is invoked as specified above).
893N/A *
893N/A * <p> If the {@code options} parameter contains the {@link
2826N/A * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps
893N/A * track of directories visited so that cycles can be detected. A cycle
893N/A * arises when there is an entry in a directory that is an ancestor of the
893N/A * directory. Cycle detection is done by recording the {@link
893N/A * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,
3471N/A * or if file keys are not available, by invoking the {@link #isSameFile
893N/A * isSameFile} method to test if a directory is the same file as an
2826N/A * ancestor. When a cycle is detected it is treated as an I/O error, and the
2826N/A * {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with
2826N/A * an instance of {@link FileSystemLoopException}.
893N/A *
893N/A * <p> The {@code maxDepth} parameter is the maximum number of levels of
893N/A * directories to visit. A value of {@code 0} means that only the starting
893N/A * file is visited, unless denied by the security manager. A value of
893N/A * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all
2826N/A * levels should be visited. The {@code visitFile} method is invoked for all
2826N/A * files, including directories, encountered at {@code maxDepth}, unless the
2826N/A * basic file attributes cannot be read, in which case the {@code
2826N/A * visitFileFailed} method is invoked.
893N/A *
893N/A * <p> If a visitor returns a result of {@code null} then {@code
893N/A * NullPointerException} is thrown.
893N/A *
893N/A * <p> When a security manager is installed and it denies access to a file
893N/A * (or directory), then it is ignored and the visitor is not invoked for
893N/A * that file (or directory).
893N/A *
893N/A * @param start
3471N/A * the starting file
893N/A * @param options
3471N/A * options to configure the traversal
893N/A * @param maxDepth
3471N/A * the maximum number of directory levels to visit
893N/A * @param visitor
3471N/A * the file visitor to invoke for each file
3471N/A *
3471N/A * @return the starting file
893N/A *
893N/A * @throws IllegalArgumentException
3471N/A * if the {@code maxDepth} parameter is negative
893N/A * @throws SecurityException
893N/A * If the security manager denies access to the starting file.
893N/A * In the case of the default provider, the {@link
893N/A * SecurityManager#checkRead(String) checkRead} method is invoked
893N/A * to check read access to the directory.
2826N/A * @throws IOException
3471N/A * if an I/O error is thrown by a visitor method
893N/A */
3471N/A public static Path walkFileTree(Path start,
893N/A Set<FileVisitOption> options,
893N/A int maxDepth,
893N/A FileVisitor<? super Path> visitor)
2826N/A throws IOException
893N/A {
893N/A if (maxDepth < 0)
893N/A throw new IllegalArgumentException("'maxDepth' is negative");
1658N/A new FileTreeWalker(options, visitor, maxDepth).walk(start);
3471N/A return start;
893N/A }
893N/A
893N/A /**
893N/A * Walks a file tree.
893N/A *
893N/A * <p> This method works as if invoking it were equivalent to evaluating the
893N/A * expression:
893N/A * <blockquote><pre>
893N/A * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)
893N/A * </pre></blockquote>
3471N/A * In other words, it does not follow symbolic links, and visits all levels
3642N/A * of the file tree.
893N/A *
893N/A * @param start
3471N/A * the starting file
893N/A * @param visitor
3471N/A * the file visitor to invoke for each file
3471N/A *
3471N/A * @return the starting file
893N/A *
893N/A * @throws SecurityException
893N/A * If the security manager denies access to the starting file.
893N/A * In the case of the default provider, the {@link
893N/A * SecurityManager#checkRead(String) checkRead} method is invoked
893N/A * to check read access to the directory.
2826N/A * @throws IOException
3471N/A * if an I/O error is thrown by a visitor method
893N/A */
3471N/A public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)
3471N/A throws IOException
3471N/A {
3471N/A return walkFileTree(start,
3471N/A EnumSet.noneOf(FileVisitOption.class),
3471N/A Integer.MAX_VALUE,
3471N/A visitor);
3471N/A }
3471N/A
3471N/A
3471N/A // -- Utility methods for simple usages --
3471N/A
3471N/A // buffer size used for reading and writing
3471N/A private static final int BUFFER_SIZE = 8192;
3471N/A
3471N/A /**
3471N/A * Opens a file for reading, returning a {@code BufferedReader} that may be
3471N/A * used to read text from the file in an efficient manner. Bytes from the
3471N/A * file are decoded into characters using the specified charset. Reading
3471N/A * commences at the beginning of the file.
3471N/A *
3471N/A * <p> The {@code Reader} methods that read from the file throw {@code
3471N/A * IOException} if a malformed or unmappable byte sequence is read.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param cs
3471N/A * the charset to use for decoding
3471N/A *
3471N/A * @return a new buffered reader, with default buffer size, to read text
3471N/A * from the file
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs opening the file
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
3471N/A *
3471N/A * @see #readAllLines
3471N/A */
3471N/A public static BufferedReader newBufferedReader(Path path, Charset cs)
2826N/A throws IOException
2826N/A {
3471N/A CharsetDecoder decoder = cs.newDecoder();
3471N/A Reader reader = new InputStreamReader(newInputStream(path), decoder);
3471N/A return new BufferedReader(reader);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Opens or creates a file for writing, returning a {@code BufferedWriter}
3471N/A * that may be used to write text to the file in an efficient manner.
3471N/A * The {@code options} parameter specifies how the the file is created or
3471N/A * opened. If no options are present then this method works as if the {@link
3471N/A * StandardOpenOption#CREATE CREATE}, {@link
3471N/A * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
3471N/A * StandardOpenOption#WRITE WRITE} options are present. In other words, it
3471N/A * opens the file for writing, creating the file if it doesn't exist, or
3471N/A * initially truncating an existing {@link #isRegularFile regular-file} to
3471N/A * a size of {@code 0} if it exists.
3471N/A *
3471N/A * <p> The {@code Writer} methods to write text throw {@code IOException}
3471N/A * if the text cannot be encoded using the specified charset.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param cs
3471N/A * the charset to use for encoding
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return a new buffered writer, with default buffer size, to write text
3471N/A * to the file
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs opening or creating the file
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported option is specified
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file.
3471N/A *
3471N/A * @see #write(Path,Iterable,Charset,OpenOption[])
3471N/A */
3471N/A public static BufferedWriter newBufferedWriter(Path path, Charset cs,
3471N/A OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A CharsetEncoder encoder = cs.newEncoder();
3471N/A Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder);
3471N/A return new BufferedWriter(writer);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Reads all bytes from an input stream and writes them to an output stream.
3471N/A */
3471N/A private static long copy(InputStream source, OutputStream sink)
3471N/A throws IOException
3471N/A {
3471N/A long nread = 0L;
3471N/A byte[] buf = new byte[BUFFER_SIZE];
3471N/A int n;
3471N/A while ((n = source.read(buf)) > 0) {
3471N/A sink.write(buf, 0, n);
3471N/A nread += n;
3471N/A }
3471N/A return nread;
893N/A }
1319N/A
1319N/A /**
3471N/A * Copies all bytes from an input stream to a file. On return, the input
3471N/A * stream will be at end of stream.
3471N/A *
3471N/A * <p> By default, the copy fails if the target file already exists or is a
3471N/A * symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING
3471N/A * REPLACE_EXISTING} option is specified, and the target file already exists,
3471N/A * then it is replaced if it is not a non-empty directory. If the target
3471N/A * file exists and is a symbolic link, then the symbolic link is replaced.
3471N/A * In this release, the {@code REPLACE_EXISTING} option is the only option
3471N/A * required to be supported by this method. Additional options may be
3471N/A * supported in future releases.
1319N/A *
3471N/A * <p> If an I/O error occurs reading from the input stream or writing to
3471N/A * the file, then it may do so after the target file has been created and
3471N/A * after some bytes have been read or written. Consequently the input
3471N/A * stream may not be at end of stream and may be in an inconsistent state.
3471N/A * It is strongly recommended that the input stream be promptly closed if an
3471N/A * I/O error occurs.
3471N/A *
3471N/A * <p> This method may block indefinitely reading from the input stream (or
3471N/A * writing to the file). The behavior for the case that the input stream is
3471N/A * <i>asynchronously closed</i> or the thread interrupted during the copy is
3471N/A * highly input stream and file system provider specific and therefore not
3471N/A * specified.
1319N/A *
3471N/A * <p> <b>Usage example</b>: Suppose we want to capture a web page and save
3471N/A * it to a file:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * URI u = URI.create("http://java.sun.com/");
3471N/A * try (InputStream in = u.toURL().openStream()) {
3471N/A * Files.copy(in, path);
3471N/A * }
3471N/A * </pre>
1319N/A *
3471N/A * @param in
3471N/A * the input stream to read from
3471N/A * @param target
3471N/A * the path to the file
3471N/A * @param options
3471N/A * options specifying how the copy should be done
3471N/A *
3471N/A * @return the number of bytes read or written
1319N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs when reading or writing
3471N/A * @throws FileAlreadyExistsException
3471N/A * if the target file exists but cannot be replaced because the
3471N/A * {@code REPLACE_EXISTING} option is not specified <i>(optional
3471N/A * specific exception)</i>
3471N/A * @throws DirectoryNotEmptyException
3471N/A * the {@code REPLACE_EXISTING} option is specified but the file
3471N/A * cannot be replaced because it is a non-empty directory
3471N/A * <i>(optional specific exception)</i> *
1319N/A * @throws UnsupportedOperationException
3471N/A * if {@code options} contains a copy option that is not supported
1319N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
1319N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file. Where the
3471N/A * {@code REPLACE_EXISTING} option is specified, the security
3471N/A * manager's {@link SecurityManager#checkDelete(String) checkDelete}
3471N/A * method is invoked to check that an existing file can be deleted.
1319N/A */
3471N/A public static long copy(InputStream in, Path target, CopyOption... options)
1319N/A throws IOException
1319N/A {
3471N/A // ensure not null before opening file
3479N/A Objects.requireNonNull(in);
3471N/A
3471N/A // check for REPLACE_EXISTING
3471N/A boolean replaceExisting = false;
3471N/A for (CopyOption opt: options) {
3471N/A if (opt == StandardCopyOption.REPLACE_EXISTING) {
3471N/A replaceExisting = true;
3471N/A } else {
3471N/A if (opt == null) {
3471N/A throw new NullPointerException("options contains 'null'");
3471N/A } else {
3471N/A throw new UnsupportedOperationException(opt + " not supported");
3471N/A }
3471N/A }
1319N/A }
1319N/A
3471N/A // attempt to delete an existing file
1319N/A SecurityException se = null;
3471N/A if (replaceExisting) {
3471N/A try {
3471N/A deleteIfExists(target);
3471N/A } catch (SecurityException x) {
3471N/A se = x;
3471N/A }
1319N/A }
3471N/A
3471N/A // attempt to create target file. If it fails with
3471N/A // FileAlreadyExistsException then it may be because the security
3471N/A // manager prevented us from deleting the file, in which case we just
3471N/A // throw the SecurityException.
3471N/A OutputStream ostream;
3471N/A try {
3471N/A ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
3471N/A StandardOpenOption.WRITE);
3471N/A } catch (FileAlreadyExistsException x) {
1319N/A if (se != null)
1319N/A throw se;
3471N/A // someone else won the race and created the file
3471N/A throw x;
1319N/A }
1319N/A
3471N/A // do the copy
3471N/A try (OutputStream out = ostream) {
3471N/A return copy(in, out);
1319N/A }
1319N/A }
1319N/A
1319N/A /**
3471N/A * Copies all bytes from a file to an output stream.
3471N/A *
3471N/A * <p> If an I/O error occurs reading from the file or writing to the output
3471N/A * stream, then it may do so after some bytes have been read or written.
3471N/A * Consequently the output stream may be in an inconsistent state. It is
3471N/A * strongly recommended that the output stream be promptly closed if an I/O
3471N/A * error occurs.
3471N/A *
3471N/A * <p> This method may block indefinitely writing to the output stream (or
3471N/A * reading from the file). The behavior for the case that the output stream
3471N/A * is <i>asynchronously closed</i> or the thread interrupted during the copy
3471N/A * is highly output stream and file system provider specific and therefore
3471N/A * not specified.
3471N/A *
3471N/A * <p> Note that if the given output stream is {@link java.io.Flushable}
3471N/A * then its {@link java.io.Flushable#flush flush} method may need to invoked
3471N/A * after this method completes so as to flush any buffered output.
3471N/A *
3471N/A * @param source
3471N/A * the path to the file
3471N/A * @param out
3471N/A * the output stream to write to
3471N/A *
3471N/A * @return the number of bytes read or written
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs when reading or writing
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
1319N/A */
3471N/A public static long copy(Path source, OutputStream out) throws IOException {
3471N/A // ensure not null before opening file
3479N/A Objects.requireNonNull(out);
3471N/A
3471N/A try (InputStream in = newInputStream(source)) {
3471N/A return copy(in, out);
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Read all the bytes from an input stream. The {@code initialSize}
3471N/A * parameter indicates the initial size of the byte[] to allocate.
3471N/A */
3471N/A private static byte[] read(InputStream source, int initialSize)
1319N/A throws IOException
1319N/A {
3471N/A int capacity = initialSize;
3471N/A byte[] buf = new byte[capacity];
3471N/A int nread = 0;
3471N/A int rem = buf.length;
3471N/A int n;
3471N/A // read to EOF which may read more or less than initialSize (eg: file
3471N/A // is truncated while we are reading)
3471N/A while ((n = source.read(buf, nread, rem)) > 0) {
3471N/A nread += n;
3471N/A rem -= n;
3471N/A assert rem >= 0;
3471N/A if (rem == 0) {
3471N/A // need larger buffer
3471N/A int newCapacity = capacity << 1;
3471N/A if (newCapacity < 0) {
3471N/A if (capacity == Integer.MAX_VALUE)
3471N/A throw new OutOfMemoryError("Required array size too large");
3471N/A newCapacity = Integer.MAX_VALUE;
3471N/A }
3471N/A rem = newCapacity - capacity;
3471N/A buf = Arrays.copyOf(buf, newCapacity);
3471N/A capacity = newCapacity;
3471N/A }
3471N/A }
3471N/A return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
3471N/A }
3471N/A
3471N/A /**
3471N/A * Read all the bytes from a file. The method ensures that the file is
3471N/A * closed when all bytes have been read or an I/O error, or other runtime
3471N/A * exception, is thrown.
3471N/A *
3471N/A * <p> Note that this method is intended for simple cases where it is
3471N/A * convenient to read all bytes into a byte array. It is not intended for
3471N/A * reading in large files.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A *
3471N/A * @return a byte array containing the bytes read from the file
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs reading from the stream
3471N/A * @throws OutOfMemoryError
3471N/A * if an array of the required size cannot be allocated, for
3471N/A * example the file is larger that {@code 2GB}
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
3471N/A */
3471N/A public static byte[] readAllBytes(Path path) throws IOException {
3471N/A long size = size(path);
3471N/A if (size > (long)Integer.MAX_VALUE)
3471N/A throw new OutOfMemoryError("Required array size too large");
3471N/A
3471N/A try (InputStream in = newInputStream(path)) {
3471N/A return read(in, (int)size);
3471N/A }
3471N/A }
3471N/A
3471N/A /**
3471N/A * Read all lines from a file. This method ensures that the file is
3471N/A * closed when all bytes have been read or an I/O error, or other runtime
3471N/A * exception, is thrown. Bytes from the file are decoded into characters
3471N/A * using the specified charset.
3471N/A *
3471N/A * <p> This method recognizes the following as line terminators:
3471N/A * <ul>
3471N/A * <li> <code>&#92;u000D</code> followed by <code>&#92;u000A</code>,
3471N/A * CARRIAGE RETURN followed by LINE FEED </li>
3471N/A * <li> <code>&#92;u000A</code>, LINE FEED </li>
3471N/A * <li> <code>&#92;u000D</code>, CARRIAGE RETURN </li>
3471N/A * </ul>
3471N/A * <p> Additional Unicode line terminators may be recognized in future
3471N/A * releases.
3471N/A *
3471N/A * <p> Note that this method is intended for simple cases where it is
3471N/A * convenient to read all lines in a single operation. It is not intended
3471N/A * for reading in large files.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param cs
3471N/A * the charset to use for decoding
3471N/A *
3471N/A * @return the lines from the file as a {@code List}; whether the {@code
3471N/A * List} is modifiable or not is implementation dependent and
3471N/A * therefore not specified
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs reading from the file or a malformed or
3471N/A * unmappable byte sequence is read
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkRead(String) checkRead}
3471N/A * method is invoked to check read access to the file.
3471N/A *
3471N/A * @see #newBufferedReader
3471N/A */
3471N/A public static List<String> readAllLines(Path path, Charset cs)
3471N/A throws IOException
3471N/A {
3471N/A try (BufferedReader reader = newBufferedReader(path, cs)) {
3471N/A List<String> result = new ArrayList<>();
3471N/A for (;;) {
3471N/A String line = reader.readLine();
3471N/A if (line == null)
3471N/A break;
3471N/A result.add(line);
3471N/A }
3471N/A return result;
1319N/A }
1319N/A }
3471N/A
3471N/A /**
3471N/A * Writes bytes to a file. The {@code options} parameter specifies how the
3471N/A * the file is created or opened. If no options are present then this method
3471N/A * works as if the {@link StandardOpenOption#CREATE CREATE}, {@link
3471N/A * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
3471N/A * StandardOpenOption#WRITE WRITE} options are present. In other words, it
3471N/A * opens the file for writing, creating the file if it doesn't exist, or
3471N/A * initially truncating an existing {@link #isRegularFile regular-file} to
3471N/A * a size of {@code 0}. All bytes in the byte array are written to the file.
3471N/A * The method ensures that the file is closed when all bytes have been
3471N/A * written (or an I/O error or other runtime exception is thrown). If an I/O
3471N/A * error occurs then it may do so after the file has created or truncated,
3471N/A * or after some bytes have been written to the file.
3471N/A *
3471N/A * <p> <b>Usage example</b>: By default the method creates a new file or
3642N/A * overwrites an existing file. Suppose you instead want to append bytes
3471N/A * to an existing file:
3471N/A * <pre>
3471N/A * Path path = ...
3471N/A * byte[] bytes = ...
3471N/A * Files.write(path, bytes, StandardOpenOption.APPEND);
3471N/A * </pre>
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param bytes
3471N/A * the byte array with the bytes to write
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return the path
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs writing to or creating the file
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported option is specified
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file.
3471N/A */
3471N/A public static Path write(Path path, byte[] bytes, OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A // ensure bytes is not null before opening file
3479N/A Objects.requireNonNull(bytes);
3471N/A
3471N/A try (OutputStream out = Files.newOutputStream(path, options)) {
3471N/A int len = bytes.length;
3471N/A int rem = len;
3471N/A while (rem > 0) {
3471N/A int n = Math.min(rem, BUFFER_SIZE);
3471N/A out.write(bytes, (len-rem), n);
3471N/A rem -= n;
3471N/A }
3471N/A }
3471N/A return path;
3471N/A }
3471N/A
3471N/A /**
3471N/A * Write lines of text to a file. Each line is a char sequence and is
3471N/A * written to the file in sequence with each line terminated by the
3471N/A * platform's line separator, as defined by the system property {@code
3471N/A * line.separator}. Characters are encoded into bytes using the specified
3471N/A * charset.
3471N/A *
3471N/A * <p> The {@code options} parameter specifies how the the file is created
3471N/A * or opened. If no options are present then this method works as if the
3471N/A * {@link StandardOpenOption#CREATE CREATE}, {@link
3471N/A * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
3471N/A * StandardOpenOption#WRITE WRITE} options are present. In other words, it
3471N/A * opens the file for writing, creating the file if it doesn't exist, or
3471N/A * initially truncating an existing {@link #isRegularFile regular-file} to
3471N/A * a size of {@code 0}. The method ensures that the file is closed when all
3471N/A * lines have been written (or an I/O error or other runtime exception is
3471N/A * thrown). If an I/O error occurs then it may do so after the file has
3471N/A * created or truncated, or after some bytes have been written to the file.
3471N/A *
3471N/A * @param path
3471N/A * the path to the file
3471N/A * @param lines
3471N/A * an object to iterate over the char sequences
3471N/A * @param cs
3471N/A * the charset to use for encoding
3471N/A * @param options
3471N/A * options specifying how the file is opened
3471N/A *
3471N/A * @return the path
3471N/A *
3471N/A * @throws IOException
3471N/A * if an I/O error occurs writing to or creating the file, or the
3471N/A * text cannot be encoded using the specified charset
3471N/A * @throws UnsupportedOperationException
3471N/A * if an unsupported option is specified
3471N/A * @throws SecurityException
3471N/A * In the case of the default provider, and a security manager is
3471N/A * installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3471N/A * method is invoked to check write access to the file.
3471N/A */
3471N/A public static Path write(Path path, Iterable<? extends CharSequence> lines,
3471N/A Charset cs, OpenOption... options)
3471N/A throws IOException
3471N/A {
3471N/A // ensure lines is not null before opening file
3479N/A Objects.requireNonNull(lines);
3471N/A CharsetEncoder encoder = cs.newEncoder();
3471N/A OutputStream out = newOutputStream(path, options);
3471N/A try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {
3471N/A for (CharSequence line: lines) {
3471N/A writer.append(line);
3471N/A writer.newLine();
3471N/A }
3471N/A }
3471N/A return path;
3471N/A }
893N/A}