Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/file/Files.java
38918 views
/*1* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.file;2627import java.io.BufferedReader;28import java.io.BufferedWriter;29import java.io.Closeable;30import java.io.File;31import java.io.IOException;32import java.io.InputStream;33import java.io.InputStreamReader;34import java.io.OutputStream;35import java.io.OutputStreamWriter;36import java.io.Reader;37import java.io.UncheckedIOException;38import java.io.Writer;39import java.nio.channels.Channels;40import java.nio.channels.FileChannel;41import java.nio.channels.SeekableByteChannel;42import java.nio.charset.Charset;43import java.nio.charset.CharsetDecoder;44import java.nio.charset.CharsetEncoder;45import java.nio.charset.StandardCharsets;46import java.nio.file.attribute.BasicFileAttributeView;47import java.nio.file.attribute.BasicFileAttributes;48import java.nio.file.attribute.DosFileAttributes; // javadoc49import java.nio.file.attribute.FileAttribute;50import java.nio.file.attribute.FileAttributeView;51import java.nio.file.attribute.FileOwnerAttributeView;52import java.nio.file.attribute.FileStoreAttributeView;53import java.nio.file.attribute.FileTime;54import java.nio.file.attribute.PosixFileAttributeView;55import java.nio.file.attribute.PosixFileAttributes;56import java.nio.file.attribute.PosixFilePermission;57import java.nio.file.attribute.UserPrincipal;58import java.nio.file.spi.FileSystemProvider;59import java.nio.file.spi.FileTypeDetector;60import java.security.AccessController;61import java.security.PrivilegedAction;62import java.util.ArrayList;63import java.util.Arrays;64import java.util.Collections;65import java.util.EnumSet;66import java.util.HashSet;67import java.util.Iterator;68import java.util.List;69import java.util.Map;70import java.util.Objects;71import java.util.ServiceLoader;72import java.util.Set;73import java.util.Spliterator;74import java.util.Spliterators;75import java.util.function.BiPredicate;76import java.util.stream.Stream;77import java.util.stream.StreamSupport;7879/**80* This class consists exclusively of static methods that operate on files,81* directories, or other types of files.82*83* <p> In most cases, the methods defined here will delegate to the associated84* file system provider to perform the file operations.85*86* @since 1.787*/8889public final class Files {90private Files() { }9192/**93* Returns the {@code FileSystemProvider} to delegate to.94*/95private static FileSystemProvider provider(Path path) {96return path.getFileSystem().provider();97}9899/**100* Convert a Closeable to a Runnable by converting checked IOException101* to UncheckedIOException102*/103private static Runnable asUncheckedRunnable(Closeable c) {104return () -> {105try {106c.close();107} catch (IOException e) {108throw new UncheckedIOException(e);109}110};111}112113// -- File contents --114115/**116* Opens a file, returning an input stream to read from the file. The stream117* will not be buffered, and is not required to support the {@link118* InputStream#mark mark} or {@link InputStream#reset reset} methods. The119* stream will be safe for access by multiple concurrent threads. Reading120* commences at the beginning of the file. Whether the returned stream is121* <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly122* file system provider specific and therefore not specified.123*124* <p> The {@code options} parameter determines how the file is opened.125* If no options are present then it is equivalent to opening the file with126* the {@link StandardOpenOption#READ READ} option. In addition to the {@code127* READ} option, an implementation may also support additional implementation128* specific options.129*130* @param path131* the path to the file to open132* @param options133* options specifying how the file is opened134*135* @return a new input stream136*137* @throws IllegalArgumentException138* if an invalid combination of options is specified139* @throws UnsupportedOperationException140* if an unsupported option is specified141* @throws IOException142* if an I/O error occurs143* @throws SecurityException144* In the case of the default provider, and a security manager is145* installed, the {@link SecurityManager#checkRead(String) checkRead}146* method is invoked to check read access to the file.147*/148public static InputStream newInputStream(Path path, OpenOption... options)149throws IOException150{151return provider(path).newInputStream(path, options);152}153154/**155* Opens or creates a file, returning an output stream that may be used to156* write bytes to the file. The resulting stream will not be buffered. The157* stream will be safe for access by multiple concurrent threads. Whether158* the returned stream is <i>asynchronously closeable</i> and/or159* <i>interruptible</i> is highly file system provider specific and160* therefore not specified.161*162* <p> This method opens or creates a file in exactly the manner specified163* by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}164* method with the exception that the {@link StandardOpenOption#READ READ}165* option may not be present in the array of options. If no options are166* present then this method works as if the {@link StandardOpenOption#CREATE167* CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING},168* and {@link StandardOpenOption#WRITE WRITE} options are present. In other169* words, it opens the file for writing, creating the file if it doesn't170* exist, or initially truncating an existing {@link #isRegularFile171* regular-file} to a size of {@code 0} if it exists.172*173* <p> <b>Usage Examples:</b>174* <pre>175* Path path = ...176*177* // truncate and overwrite an existing file, or create the file if178* // it doesn't initially exist179* OutputStream out = Files.newOutputStream(path);180*181* // append to an existing file, fail if the file does not exist182* out = Files.newOutputStream(path, APPEND);183*184* // append to an existing file, create file if it doesn't initially exist185* out = Files.newOutputStream(path, CREATE, APPEND);186*187* // always create new file, failing if it already exists188* out = Files.newOutputStream(path, CREATE_NEW);189* </pre>190*191* @param path192* the path to the file to open or create193* @param options194* options specifying how the file is opened195*196* @return a new output stream197*198* @throws IllegalArgumentException199* if {@code options} contains an invalid combination of options200* @throws UnsupportedOperationException201* if an unsupported option is specified202* @throws IOException203* if an I/O error occurs204* @throws SecurityException205* In the case of the default provider, and a security manager is206* installed, the {@link SecurityManager#checkWrite(String) checkWrite}207* method is invoked to check write access to the file. The {@link208* SecurityManager#checkDelete(String) checkDelete} method is209* invoked to check delete access if the file is opened with the210* {@code DELETE_ON_CLOSE} option.211*/212public static OutputStream newOutputStream(Path path, OpenOption... options)213throws IOException214{215return provider(path).newOutputStream(path, options);216}217218/**219* Opens or creates a file, returning a seekable byte channel to access the220* file.221*222* <p> The {@code options} parameter determines how the file is opened.223* The {@link StandardOpenOption#READ READ} and {@link224* StandardOpenOption#WRITE WRITE} options determine if the file should be225* opened for reading and/or writing. If neither option (or the {@link226* StandardOpenOption#APPEND APPEND} option) is present then the file is227* opened for reading. By default reading or writing commence at the228* beginning of the file.229*230* <p> In the addition to {@code READ} and {@code WRITE}, the following231* options may be present:232*233* <table border=1 cellpadding=5 summary="Options">234* <tr> <th>Option</th> <th>Description</th> </tr>235* <tr>236* <td> {@link StandardOpenOption#APPEND APPEND} </td>237* <td> If this option is present then the file is opened for writing and238* each invocation of the channel's {@code write} method first advances239* the position to the end of the file and then writes the requested240* data. Whether the advancement of the position and the writing of the241* data are done in a single atomic operation is system-dependent and242* therefore unspecified. This option may not be used in conjunction243* with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>244* </tr>245* <tr>246* <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>247* <td> If this option is present then the existing file is truncated to248* a size of 0 bytes. This option is ignored when the file is opened only249* for reading. </td>250* </tr>251* <tr>252* <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>253* <td> If this option is present then a new file is created, failing if254* the file already exists or is a symbolic link. When creating a file the255* check for the existence of the file and the creation of the file if it256* does not exist is atomic with respect to other file system operations.257* This option is ignored when the file is opened only for reading. </td>258* </tr>259* <tr>260* <td > {@link StandardOpenOption#CREATE CREATE} </td>261* <td> If this option is present then an existing file is opened if it262* exists, otherwise a new file is created. This option is ignored if the263* {@code CREATE_NEW} option is also present or the file is opened only264* for reading. </td>265* </tr>266* <tr>267* <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>268* <td> When this option is present then the implementation makes a269* <em>best effort</em> attempt to delete the file when closed by the270* {@link SeekableByteChannel#close close} method. If the {@code close}271* method is not invoked then a <em>best effort</em> attempt is made to272* delete the file when the Java virtual machine terminates. </td>273* </tr>274* <tr>275* <td>{@link StandardOpenOption#SPARSE SPARSE} </td>276* <td> When creating a new file this option is a <em>hint</em> that the277* new file will be sparse. This option is ignored when not creating278* a new file. </td>279* </tr>280* <tr>281* <td> {@link StandardOpenOption#SYNC SYNC} </td>282* <td> Requires that every update to the file's content or metadata be283* written synchronously to the underlying storage device. (see <a284* href="package-summary.html#integrity"> Synchronized I/O file285* integrity</a>). </td>286* </tr>287* <tr>288* <td> {@link StandardOpenOption#DSYNC DSYNC} </td>289* <td> Requires that every update to the file's content be written290* synchronously to the underlying storage device. (see <a291* href="package-summary.html#integrity"> Synchronized I/O file292* integrity</a>). </td>293* </tr>294* </table>295*296* <p> An implementation may also support additional implementation specific297* options.298*299* <p> The {@code attrs} parameter is optional {@link FileAttribute300* file-attributes} to set atomically when a new file is created.301*302* <p> In the case of the default provider, the returned seekable byte channel303* is a {@link java.nio.channels.FileChannel}.304*305* <p> <b>Usage Examples:</b>306* <pre>307* Path path = ...308*309* // open file for reading310* ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ)));311*312* // open file for writing to the end of an existing file, creating313* // the file if it doesn't already exist314* WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND));315*316* // create file with initial permissions, opening it for both reading and writing317* {@code FileAttribute<Set<PosixFilePermission>> perms = ...}318* SeekableByteChannel sbc = Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms);319* </pre>320*321* @param path322* the path to the file to open or create323* @param options324* options specifying how the file is opened325* @param attrs326* an optional list of file attributes to set atomically when327* creating the file328*329* @return a new seekable byte channel330*331* @throws IllegalArgumentException332* if the set contains an invalid combination of options333* @throws UnsupportedOperationException334* if an unsupported open option is specified or the array contains335* attributes that cannot be set atomically when creating the file336* @throws FileAlreadyExistsException337* if a file of that name already exists and the {@link338* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified339* <i>(optional specific exception)</i>340* @throws IOException341* if an I/O error occurs342* @throws SecurityException343* In the case of the default provider, and a security manager is344* installed, the {@link SecurityManager#checkRead(String) checkRead}345* method is invoked to check read access to the path if the file is346* opened for reading. The {@link SecurityManager#checkWrite(String)347* checkWrite} method is invoked to check write access to the path348* if the file is opened for writing. The {@link349* SecurityManager#checkDelete(String) checkDelete} method is350* invoked to check delete access if the file is opened with the351* {@code DELETE_ON_CLOSE} option.352*353* @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[])354*/355public static SeekableByteChannel newByteChannel(Path path,356Set<? extends OpenOption> options,357FileAttribute<?>... attrs)358throws IOException359{360return provider(path).newByteChannel(path, options, attrs);361}362363/**364* Opens or creates a file, returning a seekable byte channel to access the365* file.366*367* <p> This method opens or creates a file in exactly the manner specified368* by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}369* method.370*371* @param path372* the path to the file to open or create373* @param options374* options specifying how the file is opened375*376* @return a new seekable byte channel377*378* @throws IllegalArgumentException379* if the set contains an invalid combination of options380* @throws UnsupportedOperationException381* if an unsupported open option is specified382* @throws FileAlreadyExistsException383* if a file of that name already exists and the {@link384* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified385* <i>(optional specific exception)</i>386* @throws IOException387* if an I/O error occurs388* @throws SecurityException389* In the case of the default provider, and a security manager is390* installed, the {@link SecurityManager#checkRead(String) checkRead}391* method is invoked to check read access to the path if the file is392* opened for reading. The {@link SecurityManager#checkWrite(String)393* checkWrite} method is invoked to check write access to the path394* if the file is opened for writing. The {@link395* SecurityManager#checkDelete(String) checkDelete} method is396* invoked to check delete access if the file is opened with the397* {@code DELETE_ON_CLOSE} option.398*399* @see java.nio.channels.FileChannel#open(Path,OpenOption[])400*/401public static SeekableByteChannel newByteChannel(Path path, OpenOption... options)402throws IOException403{404Set<OpenOption> set = new HashSet<OpenOption>(options.length);405Collections.addAll(set, options);406return newByteChannel(path, set);407}408409// -- Directories --410411private static class AcceptAllFilter412implements DirectoryStream.Filter<Path>413{414private AcceptAllFilter() { }415416@Override417public boolean accept(Path entry) { return true; }418419static final AcceptAllFilter FILTER = new AcceptAllFilter();420}421422/**423* Opens a directory, returning a {@link DirectoryStream} to iterate over424* all entries in the directory. The elements returned by the directory425* stream's {@link DirectoryStream#iterator iterator} are of type {@code426* Path}, each one representing an entry in the directory. The {@code Path}427* objects are obtained as if by {@link Path#resolve(Path) resolving} the428* name of the directory entry against {@code dir}.429*430* <p> When not using the try-with-resources construct, then directory431* stream's {@code close} method should be invoked after iteration is432* completed so as to free any resources held for the open directory.433*434* <p> When an implementation supports operations on entries in the435* directory that execute in a race-free manner then the returned directory436* stream is a {@link SecureDirectoryStream}.437*438* @param dir439* the path to the directory440*441* @return a new and open {@code DirectoryStream} object442*443* @throws NotDirectoryException444* if the file could not otherwise be opened because it is not445* a directory <i>(optional specific exception)</i>446* @throws IOException447* if an I/O error occurs448* @throws SecurityException449* In the case of the default provider, and a security manager is450* installed, the {@link SecurityManager#checkRead(String) checkRead}451* method is invoked to check read access to the directory.452*/453public static DirectoryStream<Path> newDirectoryStream(Path dir)454throws IOException455{456return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER);457}458459/**460* Opens a directory, returning a {@link DirectoryStream} to iterate over461* the entries in the directory. The elements returned by the directory462* stream's {@link DirectoryStream#iterator iterator} are of type {@code463* Path}, each one representing an entry in the directory. The {@code Path}464* objects are obtained as if by {@link Path#resolve(Path) resolving} the465* name of the directory entry against {@code dir}. The entries returned by466* the iterator are filtered by matching the {@code String} representation467* of their file names against the given <em>globbing</em> pattern.468*469* <p> For example, suppose we want to iterate over the files ending with470* ".java" in a directory:471* <pre>472* Path dir = ...473* try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) {474* :475* }476* </pre>477*478* <p> The globbing pattern is specified by the {@link479* FileSystem#getPathMatcher getPathMatcher} method.480*481* <p> When not using the try-with-resources construct, then directory482* stream's {@code close} method should be invoked after iteration is483* completed so as to free any resources held for the open directory.484*485* <p> When an implementation supports operations on entries in the486* directory that execute in a race-free manner then the returned directory487* stream is a {@link SecureDirectoryStream}.488*489* @param dir490* the path to the directory491* @param glob492* the glob pattern493*494* @return a new and open {@code DirectoryStream} object495*496* @throws java.util.regex.PatternSyntaxException497* if the pattern is invalid498* @throws NotDirectoryException499* if the file could not otherwise be opened because it is not500* a directory <i>(optional specific exception)</i>501* @throws IOException502* if an I/O error occurs503* @throws SecurityException504* In the case of the default provider, and a security manager is505* installed, the {@link SecurityManager#checkRead(String) checkRead}506* method is invoked to check read access to the directory.507*/508public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob)509throws IOException510{511// avoid creating a matcher if all entries are required.512if (glob.equals("*"))513return newDirectoryStream(dir);514515// create a matcher and return a filter that uses it.516FileSystem fs = dir.getFileSystem();517final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);518DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {519@Override520public boolean accept(Path entry) {521return matcher.matches(entry.getFileName());522}523};524return fs.provider().newDirectoryStream(dir, filter);525}526527/**528* Opens a directory, returning a {@link DirectoryStream} to iterate over529* the entries in the directory. The elements returned by the directory530* stream's {@link DirectoryStream#iterator iterator} are of type {@code531* Path}, each one representing an entry in the directory. The {@code Path}532* objects are obtained as if by {@link Path#resolve(Path) resolving} the533* name of the directory entry against {@code dir}. The entries returned by534* the iterator are filtered by the given {@link DirectoryStream.Filter535* filter}.536*537* <p> When not using the try-with-resources construct, then directory538* stream's {@code close} method should be invoked after iteration is539* completed so as to free any resources held for the open directory.540*541* <p> Where the filter terminates due to an uncaught error or runtime542* exception then it is propagated to the {@link Iterator#hasNext()543* hasNext} or {@link Iterator#next() next} method. Where an {@code544* IOException} is thrown, it results in the {@code hasNext} or {@code545* next} method throwing a {@link DirectoryIteratorException} with the546* {@code IOException} as the cause.547*548* <p> When an implementation supports operations on entries in the549* directory that execute in a race-free manner then the returned directory550* stream is a {@link SecureDirectoryStream}.551*552* <p> <b>Usage Example:</b>553* Suppose we want to iterate over the files in a directory that are554* larger than 8K.555* <pre>556* DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {557* public boolean accept(Path file) throws IOException {558* return (Files.size(file) > 8192L);559* }560* };561* Path dir = ...562* try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {563* :564* }565* </pre>566*567* @param dir568* the path to the directory569* @param filter570* the directory stream filter571*572* @return a new and open {@code DirectoryStream} object573*574* @throws NotDirectoryException575* if the file could not otherwise be opened because it is not576* a directory <i>(optional specific exception)</i>577* @throws IOException578* if an I/O error occurs579* @throws SecurityException580* In the case of the default provider, and a security manager is581* installed, the {@link SecurityManager#checkRead(String) checkRead}582* method is invoked to check read access to the directory.583*/584public static DirectoryStream<Path> newDirectoryStream(Path dir,585DirectoryStream.Filter<? super Path> filter)586throws IOException587{588return provider(dir).newDirectoryStream(dir, filter);589}590591// -- Creation and deletion --592593/**594* Creates a new and empty file, failing if the file already exists. The595* check for the existence of the file and the creation of the new file if596* it does not exist are a single operation that is atomic with respect to597* all other filesystem activities that might affect the directory.598*599* <p> The {@code attrs} parameter is optional {@link FileAttribute600* file-attributes} to set atomically when creating the file. Each attribute601* is identified by its {@link FileAttribute#name name}. If more than one602* attribute of the same name is included in the array then all but the last603* occurrence is ignored.604*605* @param path606* the path to the file to create607* @param attrs608* an optional list of file attributes to set atomically when609* creating the file610*611* @return the file612*613* @throws UnsupportedOperationException614* if the array contains an attribute that cannot be set atomically615* when creating the file616* @throws FileAlreadyExistsException617* if a file of that name already exists618* <i>(optional specific exception)</i>619* @throws IOException620* if an I/O error occurs or the parent directory does not exist621* @throws SecurityException622* In the case of the default provider, and a security manager is623* installed, the {@link SecurityManager#checkWrite(String) checkWrite}624* method is invoked to check write access to the new file.625*/626public static Path createFile(Path path, FileAttribute<?>... attrs)627throws IOException628{629EnumSet<StandardOpenOption> options =630EnumSet.<StandardOpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);631newByteChannel(path, options, attrs).close();632return path;633}634635/**636* Creates a new directory. The check for the existence of the file and the637* creation of the directory if it does not exist are a single operation638* that is atomic with respect to all other filesystem activities that might639* affect the directory. The {@link #createDirectories createDirectories}640* method should be used where it is required to create all nonexistent641* parent directories first.642*643* <p> The {@code attrs} parameter is optional {@link FileAttribute644* file-attributes} to set atomically when creating the directory. Each645* attribute is identified by its {@link FileAttribute#name name}. If more646* than one attribute of the same name is included in the array then all but647* the last occurrence is ignored.648*649* @param dir650* the directory to create651* @param attrs652* an optional list of file attributes to set atomically when653* creating the directory654*655* @return the directory656*657* @throws UnsupportedOperationException658* if the array contains an attribute that cannot be set atomically659* when creating the directory660* @throws FileAlreadyExistsException661* if a directory could not otherwise be created because a file of662* that name already exists <i>(optional specific exception)</i>663* @throws IOException664* if an I/O error occurs or the parent directory does not exist665* @throws SecurityException666* In the case of the default provider, and a security manager is667* installed, the {@link SecurityManager#checkWrite(String) checkWrite}668* method is invoked to check write access to the new directory.669*/670public static Path createDirectory(Path dir, FileAttribute<?>... attrs)671throws IOException672{673provider(dir).createDirectory(dir, attrs);674return dir;675}676677/**678* Creates a directory by creating all nonexistent parent directories first.679* Unlike the {@link #createDirectory createDirectory} method, an exception680* is not thrown if the directory could not be created because it already681* exists.682*683* <p> The {@code attrs} parameter is optional {@link FileAttribute684* file-attributes} to set atomically when creating the nonexistent685* directories. Each file attribute is identified by its {@link686* FileAttribute#name name}. If more than one attribute of the same name is687* included in the array then all but the last occurrence is ignored.688*689* <p> If this method fails, then it may do so after creating some, but not690* all, of the parent directories.691*692* @param dir693* the directory to create694*695* @param attrs696* an optional list of file attributes to set atomically when697* creating the directory698*699* @return the directory700*701* @throws UnsupportedOperationException702* if the array contains an attribute that cannot be set atomically703* when creating the directory704* @throws FileAlreadyExistsException705* if {@code dir} exists but is not a directory <i>(optional specific706* exception)</i>707* @throws IOException708* if an I/O error occurs709* @throws SecurityException710* in the case of the default provider, and a security manager is711* installed, the {@link SecurityManager#checkWrite(String) checkWrite}712* method is invoked prior to attempting to create a directory and713* its {@link SecurityManager#checkRead(String) checkRead} is714* invoked for each parent directory that is checked. If {@code715* dir} is not an absolute path then its {@link Path#toAbsolutePath716* toAbsolutePath} may need to be invoked to get its absolute path.717* This may invoke the security manager's {@link718* SecurityManager#checkPropertyAccess(String) checkPropertyAccess}719* method to check access to the system property {@code user.dir}720*/721public static Path createDirectories(Path dir, FileAttribute<?>... attrs)722throws IOException723{724// attempt to create the directory725try {726createAndCheckIsDirectory(dir, attrs);727return dir;728} catch (FileAlreadyExistsException x) {729// file exists and is not a directory730throw x;731} catch (IOException x) {732// parent may not exist or other reason733}734SecurityException se = null;735try {736dir = dir.toAbsolutePath();737} catch (SecurityException x) {738// don't have permission to get absolute path739se = x;740}741// find a decendent that exists742Path parent = dir.getParent();743while (parent != null) {744try {745provider(parent).checkAccess(parent);746break;747} catch (NoSuchFileException x) {748// does not exist749}750parent = parent.getParent();751}752if (parent == null) {753// unable to find existing parent754if (se == null) {755throw new FileSystemException(dir.toString(), null,756"Unable to determine if root directory exists");757} else {758throw se;759}760}761762// create directories763Path child = parent;764for (Path name: parent.relativize(dir)) {765child = child.resolve(name);766createAndCheckIsDirectory(child, attrs);767}768return dir;769}770771/**772* Used by createDirectories to attempt to create a directory. A no-op773* if the directory already exists.774*/775private static void createAndCheckIsDirectory(Path dir,776FileAttribute<?>... attrs)777throws IOException778{779try {780createDirectory(dir, attrs);781} catch (FileAlreadyExistsException x) {782if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS))783throw x;784}785}786787/**788* Creates a new empty file in the specified directory, using the given789* prefix and suffix strings to generate its name. The resulting790* {@code Path} is associated with the same {@code FileSystem} as the given791* directory.792*793* <p> The details as to how the name of the file is constructed is794* implementation dependent and therefore not specified. Where possible795* the {@code prefix} and {@code suffix} are used to construct candidate796* names in the same manner as the {@link797* java.io.File#createTempFile(String,String,File)} method.798*799* <p> As with the {@code File.createTempFile} methods, this method is only800* part of a temporary-file facility. Where used as a <em>work files</em>,801* the resulting file may be opened using the {@link802* StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the803* file is deleted when the appropriate {@code close} method is invoked.804* Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the805* {@link java.io.File#deleteOnExit} mechanism may be used to delete the806* file automatically.807*808* <p> The {@code attrs} parameter is optional {@link FileAttribute809* file-attributes} to set atomically when creating the file. Each attribute810* is identified by its {@link FileAttribute#name name}. If more than one811* attribute of the same name is included in the array then all but the last812* occurrence is ignored. When no file attributes are specified, then the813* resulting file may have more restrictive access permissions to files814* created by the {@link java.io.File#createTempFile(String,String,File)}815* method.816*817* @param dir818* the path to directory in which to create the file819* @param prefix820* the prefix string to be used in generating the file's name;821* may be {@code null}822* @param suffix823* the suffix string to be used in generating the file's name;824* may be {@code null}, in which case "{@code .tmp}" is used825* @param attrs826* an optional list of file attributes to set atomically when827* creating the file828*829* @return the path to the newly created file that did not exist before830* this method was invoked831*832* @throws IllegalArgumentException833* if the prefix or suffix parameters cannot be used to generate834* a candidate file name835* @throws UnsupportedOperationException836* if the array contains an attribute that cannot be set atomically837* when creating the directory838* @throws IOException839* if an I/O error occurs or {@code dir} does not exist840* @throws SecurityException841* In the case of the default provider, and a security manager is842* installed, the {@link SecurityManager#checkWrite(String) checkWrite}843* method is invoked to check write access to the file.844*/845public static Path createTempFile(Path dir,846String prefix,847String suffix,848FileAttribute<?>... attrs)849throws IOException850{851return TempFileHelper.createTempFile(Objects.requireNonNull(dir),852prefix, suffix, attrs);853}854855/**856* Creates an empty file in the default temporary-file directory, using857* the given prefix and suffix to generate its name. The resulting {@code858* Path} is associated with the default {@code FileSystem}.859*860* <p> This method works in exactly the manner specified by the861* {@link #createTempFile(Path,String,String,FileAttribute[])} method for862* the case that the {@code dir} parameter is the temporary-file directory.863*864* @param prefix865* the prefix string to be used in generating the file's name;866* may be {@code null}867* @param suffix868* the suffix string to be used in generating the file's name;869* may be {@code null}, in which case "{@code .tmp}" is used870* @param attrs871* an optional list of file attributes to set atomically when872* creating the file873*874* @return the path to the newly created file that did not exist before875* this method was invoked876*877* @throws IllegalArgumentException878* if the prefix or suffix parameters cannot be used to generate879* a candidate file name880* @throws UnsupportedOperationException881* if the array contains an attribute that cannot be set atomically882* when creating the directory883* @throws IOException884* if an I/O error occurs or the temporary-file directory does not885* exist886* @throws SecurityException887* In the case of the default provider, and a security manager is888* installed, the {@link SecurityManager#checkWrite(String) checkWrite}889* method is invoked to check write access to the file.890*/891public static Path createTempFile(String prefix,892String suffix,893FileAttribute<?>... attrs)894throws IOException895{896return TempFileHelper.createTempFile(null, prefix, suffix, attrs);897}898899/**900* Creates a new directory in the specified directory, using the given901* prefix to generate its name. The resulting {@code Path} is associated902* with the same {@code FileSystem} as the given directory.903*904* <p> The details as to how the name of the directory is constructed is905* implementation dependent and therefore not specified. Where possible906* the {@code prefix} is used to construct candidate names.907*908* <p> As with the {@code createTempFile} methods, this method is only909* part of a temporary-file facility. A {@link Runtime#addShutdownHook910* shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be911* used to delete the directory automatically.912*913* <p> The {@code attrs} parameter is optional {@link FileAttribute914* file-attributes} to set atomically when creating the directory. Each915* attribute is identified by its {@link FileAttribute#name name}. If more916* than one attribute of the same name is included in the array then all but917* the last occurrence is ignored.918*919* @param dir920* the path to directory in which to create the directory921* @param prefix922* the prefix string to be used in generating the directory's name;923* may be {@code null}924* @param attrs925* an optional list of file attributes to set atomically when926* creating the directory927*928* @return the path to the newly created directory that did not exist before929* this method was invoked930*931* @throws IllegalArgumentException932* if the prefix cannot be used to generate a candidate directory name933* @throws UnsupportedOperationException934* if the array contains an attribute that cannot be set atomically935* when creating the directory936* @throws IOException937* if an I/O error occurs or {@code dir} does not exist938* @throws SecurityException939* In the case of the default provider, and a security manager is940* installed, the {@link SecurityManager#checkWrite(String) checkWrite}941* method is invoked to check write access when creating the942* directory.943*/944public static Path createTempDirectory(Path dir,945String prefix,946FileAttribute<?>... attrs)947throws IOException948{949return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir),950prefix, attrs);951}952953/**954* Creates a new directory in the default temporary-file directory, using955* the given prefix to generate its name. The resulting {@code Path} is956* associated with the default {@code FileSystem}.957*958* <p> This method works in exactly the manner specified by {@link959* #createTempDirectory(Path,String,FileAttribute[])} method for the case960* that the {@code dir} parameter is the temporary-file directory.961*962* @param prefix963* the prefix string to be used in generating the directory's name;964* may be {@code null}965* @param attrs966* an optional list of file attributes to set atomically when967* creating the directory968*969* @return the path to the newly created directory that did not exist before970* this method was invoked971*972* @throws IllegalArgumentException973* if the prefix cannot be used to generate a candidate directory name974* @throws UnsupportedOperationException975* if the array contains an attribute that cannot be set atomically976* when creating the directory977* @throws IOException978* if an I/O error occurs or the temporary-file directory does not979* exist980* @throws SecurityException981* In the case of the default provider, and a security manager is982* installed, the {@link SecurityManager#checkWrite(String) checkWrite}983* method is invoked to check write access when creating the984* directory.985*/986public static Path createTempDirectory(String prefix,987FileAttribute<?>... attrs)988throws IOException989{990return TempFileHelper.createTempDirectory(null, prefix, attrs);991}992993/**994* Creates a symbolic link to a target <i>(optional operation)</i>.995*996* <p> The {@code target} parameter is the target of the link. It may be an997* {@link Path#isAbsolute absolute} or relative path and may not exist. When998* the target is a relative path then file system operations on the resulting999* link are relative to the path of the link.1000*1001* <p> The {@code attrs} parameter is optional {@link FileAttribute1002* attributes} to set atomically when creating the link. Each attribute is1003* identified by its {@link FileAttribute#name name}. If more than one attribute1004* of the same name is included in the array then all but the last occurrence1005* is ignored.1006*1007* <p> Where symbolic links are supported, but the underlying {@link FileStore}1008* does not support symbolic links, then this may fail with an {@link1009* IOException}. Additionally, some operating systems may require that the1010* Java virtual machine be started with implementation specific privileges to1011* create symbolic links, in which case this method may throw {@code IOException}.1012*1013* @param link1014* the path of the symbolic link to create1015* @param target1016* the target of the symbolic link1017* @param attrs1018* the array of attributes to set atomically when creating the1019* symbolic link1020*1021* @return the path to the symbolic link1022*1023* @throws UnsupportedOperationException1024* if the implementation does not support symbolic links or the1025* array contains an attribute that cannot be set atomically when1026* creating the symbolic link1027* @throws FileAlreadyExistsException1028* if a file with the name already exists <i>(optional specific1029* exception)</i>1030* @throws IOException1031* if an I/O error occurs1032* @throws SecurityException1033* In the case of the default provider, and a security manager1034* is installed, it denies {@link LinkPermission}<tt>("symbolic")</tt>1035* or its {@link SecurityManager#checkWrite(String) checkWrite}1036* method denies write access to the path of the symbolic link.1037*/1038public static Path createSymbolicLink(Path link, Path target,1039FileAttribute<?>... attrs)1040throws IOException1041{1042provider(link).createSymbolicLink(link, target, attrs);1043return link;1044}10451046/**1047* Creates a new link (directory entry) for an existing file <i>(optional1048* operation)</i>.1049*1050* <p> The {@code link} parameter locates the directory entry to create.1051* The {@code existing} parameter is the path to an existing file. This1052* method creates a new directory entry for the file so that it can be1053* accessed using {@code link} as the path. On some file systems this is1054* known as creating a "hard link". Whether the file attributes are1055* maintained for the file or for each directory entry is file system1056* specific and therefore not specified. Typically, a file system requires1057* that all links (directory entries) for a file be on the same file system.1058* Furthermore, on some platforms, the Java virtual machine may require to1059* be started with implementation specific privileges to create hard links1060* or to create links to directories.1061*1062* @param link1063* the link (directory entry) to create1064* @param existing1065* a path to an existing file1066*1067* @return the path to the link (directory entry)1068*1069* @throws UnsupportedOperationException1070* if the implementation does not support adding an existing file1071* to a directory1072* @throws FileAlreadyExistsException1073* if the entry could not otherwise be created because a file of1074* that name already exists <i>(optional specific exception)</i>1075* @throws IOException1076* if an I/O error occurs1077* @throws SecurityException1078* In the case of the default provider, and a security manager1079* is installed, it denies {@link LinkPermission}<tt>("hard")</tt>1080* or its {@link SecurityManager#checkWrite(String) checkWrite}1081* method denies write access to either the link or the1082* existing file.1083*/1084public static Path createLink(Path link, Path existing) throws IOException {1085provider(link).createLink(link, existing);1086return link;1087}10881089/**1090* Deletes a file.1091*1092* <p> An implementation may require to examine the file to determine if the1093* file is a directory. Consequently this method may not be atomic with respect1094* to other file system operations. If the file is a symbolic link then the1095* symbolic link itself, not the final target of the link, is deleted.1096*1097* <p> If the file is a directory then the directory must be empty. In some1098* implementations a directory has entries for special files or links that1099* are created when the directory is created. In such implementations a1100* directory is considered empty when only the special entries exist.1101* This method can be used with the {@link #walkFileTree walkFileTree}1102* method to delete a directory and all entries in the directory, or an1103* entire <i>file-tree</i> where required.1104*1105* <p> On some operating systems it may not be possible to remove a file when1106* it is open and in use by this Java virtual machine or other programs.1107*1108* @param path1109* the path to the file to delete1110*1111* @throws NoSuchFileException1112* if the file does not exist <i>(optional specific exception)</i>1113* @throws DirectoryNotEmptyException1114* if the file is a directory and could not otherwise be deleted1115* because the directory is not empty <i>(optional specific1116* exception)</i>1117* @throws IOException1118* if an I/O error occurs1119* @throws SecurityException1120* In the case of the default provider, and a security manager is1121* installed, the {@link SecurityManager#checkDelete(String)} method1122* is invoked to check delete access to the file1123*/1124public static void delete(Path path) throws IOException {1125provider(path).delete(path);1126}11271128/**1129* Deletes a file if it exists.1130*1131* <p> As with the {@link #delete(Path) delete(Path)} method, an1132* implementation may need to examine the file to determine if the file is a1133* directory. Consequently this method may not be atomic with respect to1134* other file system operations. If the file is a symbolic link, then the1135* symbolic link itself, not the final target of the link, is deleted.1136*1137* <p> If the file is a directory then the directory must be empty. In some1138* implementations a directory has entries for special files or links that1139* are created when the directory is created. In such implementations a1140* directory is considered empty when only the special entries exist.1141*1142* <p> On some operating systems it may not be possible to remove a file when1143* it is open and in use by this Java virtual machine or other programs.1144*1145* @param path1146* the path to the file to delete1147*1148* @return {@code true} if the file was deleted by this method; {@code1149* false} if the file could not be deleted because it did not1150* exist1151*1152* @throws DirectoryNotEmptyException1153* if the file is a directory and could not otherwise be deleted1154* because the directory is not empty <i>(optional specific1155* exception)</i>1156* @throws IOException1157* if an I/O error occurs1158* @throws SecurityException1159* In the case of the default provider, and a security manager is1160* installed, the {@link SecurityManager#checkDelete(String)} method1161* is invoked to check delete access to the file.1162*/1163public static boolean deleteIfExists(Path path) throws IOException {1164return provider(path).deleteIfExists(path);1165}11661167// -- Copying and moving files --11681169/**1170* Copy a file to a target file.1171*1172* <p> This method copies a file to the target file with the {@code1173* options} parameter specifying how the copy is performed. By default, the1174* copy fails if the target file already exists or is a symbolic link,1175* except if the source and target are the {@link #isSameFile same} file, in1176* which case the method completes without copying the file. File attributes1177* are not required to be copied to the target file. If symbolic links are1178* supported, and the file is a symbolic link, then the final target of the1179* link is copied. If the file is a directory then it creates an empty1180* directory in the target location (entries in the directory are not1181* copied). This method can be used with the {@link #walkFileTree1182* walkFileTree} method to copy a directory and all entries in the directory,1183* or an entire <i>file-tree</i> where required.1184*1185* <p> The {@code options} parameter may include any of the following:1186*1187* <table border=1 cellpadding=5 summary="">1188* <tr> <th>Option</th> <th>Description</th> </tr>1189* <tr>1190* <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td>1191* <td> If the target file exists, then the target file is replaced if it1192* is not a non-empty directory. If the target file exists and is a1193* symbolic link, then the symbolic link itself, not the target of1194* the link, is replaced. </td>1195* </tr>1196* <tr>1197* <td> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </td>1198* <td> Attempts to copy the file attributes associated with this file to1199* the target file. The exact file attributes that are copied is platform1200* and file system dependent and therefore unspecified. Minimally, the1201* {@link BasicFileAttributes#lastModifiedTime last-modified-time} is1202* copied to the target file if supported by both the source and target1203* file stores. Copying of file timestamps may result in precision1204* loss. </td>1205* </tr>1206* <tr>1207* <td> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </td>1208* <td> Symbolic links are not followed. If the file is a symbolic link,1209* then the symbolic link itself, not the target of the link, is copied.1210* It is implementation specific if file attributes can be copied to the1211* new link. In other words, the {@code COPY_ATTRIBUTES} option may be1212* ignored when copying a symbolic link. </td>1213* </tr>1214* </table>1215*1216* <p> An implementation of this interface may support additional1217* implementation specific options.1218*1219* <p> Copying a file is not an atomic operation. If an {@link IOException}1220* is thrown, then it is possible that the target file is incomplete or some1221* of its file attributes have not been copied from the source file. When1222* the {@code REPLACE_EXISTING} option is specified and the target file1223* exists, then the target file is replaced. The check for the existence of1224* the file and the creation of the new file may not be atomic with respect1225* to other file system activities.1226*1227* <p> <b>Usage Example:</b>1228* Suppose we want to copy a file into a directory, giving it the same file1229* name as the source file:1230* <pre>1231* Path source = ...1232* Path newdir = ...1233* Files.copy(source, newdir.resolve(source.getFileName());1234* </pre>1235*1236* @param source1237* the path to the file to copy1238* @param target1239* the path to the target file (may be associated with a different1240* provider to the source path)1241* @param options1242* options specifying how the copy should be done1243*1244* @return the path to the target file1245*1246* @throws UnsupportedOperationException1247* if the array contains a copy option that is not supported1248* @throws FileAlreadyExistsException1249* if the target file exists but cannot be replaced because the1250* {@code REPLACE_EXISTING} option is not specified <i>(optional1251* specific exception)</i>1252* @throws DirectoryNotEmptyException1253* the {@code REPLACE_EXISTING} option is specified but the file1254* cannot be replaced because it is a non-empty directory1255* <i>(optional specific exception)</i>1256* @throws IOException1257* if an I/O error occurs1258* @throws SecurityException1259* In the case of the default provider, and a security manager is1260* installed, the {@link SecurityManager#checkRead(String) checkRead}1261* method is invoked to check read access to the source file, the1262* {@link SecurityManager#checkWrite(String) checkWrite} is invoked1263* to check write access to the target file. If a symbolic link is1264* copied the security manager is invoked to check {@link1265* LinkPermission}{@code ("symbolic")}.1266*/1267public static Path copy(Path source, Path target, CopyOption... options)1268throws IOException1269{1270FileSystemProvider provider = provider(source);1271if (provider(target) == provider) {1272// same provider1273provider.copy(source, target, options);1274} else {1275// different providers1276CopyMoveHelper.copyToForeignTarget(source, target, options);1277}1278return target;1279}12801281/**1282* Move or rename a file to a target file.1283*1284* <p> By default, this method attempts to move the file to the target1285* file, failing if the target file exists except if the source and1286* target are the {@link #isSameFile same} file, in which case this method1287* has no effect. If the file is a symbolic link then the symbolic link1288* itself, not the target of the link, is moved. This method may be1289* invoked to move an empty directory. In some implementations a directory1290* has entries for special files or links that are created when the1291* directory is created. In such implementations a directory is considered1292* empty when only the special entries exist. When invoked to move a1293* directory that is not empty then the directory is moved if it does not1294* require moving the entries in the directory. For example, renaming a1295* directory on the same {@link FileStore} will usually not require moving1296* the entries in the directory. When moving a directory requires that its1297* entries be moved then this method fails (by throwing an {@code1298* IOException}). To move a <i>file tree</i> may involve copying rather1299* than moving directories and this can be done using the {@link1300* #copy copy} method in conjunction with the {@link1301* #walkFileTree Files.walkFileTree} utility method.1302*1303* <p> The {@code options} parameter may include any of the following:1304*1305* <table border=1 cellpadding=5 summary="">1306* <tr> <th>Option</th> <th>Description</th> </tr>1307* <tr>1308* <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td>1309* <td> If the target file exists, then the target file is replaced if it1310* is not a non-empty directory. If the target file exists and is a1311* symbolic link, then the symbolic link itself, not the target of1312* the link, is replaced. </td>1313* </tr>1314* <tr>1315* <td> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </td>1316* <td> The move is performed as an atomic file system operation and all1317* other options are ignored. If the target file exists then it is1318* implementation specific if the existing file is replaced or this method1319* fails by throwing an {@link IOException}. If the move cannot be1320* performed as an atomic file system operation then {@link1321* AtomicMoveNotSupportedException} is thrown. This can arise, for1322* example, when the target location is on a different {@code FileStore}1323* and would require that the file be copied, or target location is1324* associated with a different provider to this object. </td>1325* </table>1326*1327* <p> An implementation of this interface may support additional1328* implementation specific options.1329*1330* <p> Moving a file will copy the {@link1331* BasicFileAttributes#lastModifiedTime last-modified-time} to the target1332* file if supported by both source and target file stores. Copying of file1333* timestamps may result in precision loss. An implementation may also1334* attempt to copy other file attributes but is not required to fail if the1335* file attributes cannot be copied. When the move is performed as1336* a non-atomic operation, and an {@code IOException} is thrown, then the1337* state of the files is not defined. The original file and the target file1338* may both exist, the target file may be incomplete or some of its file1339* attributes may not been copied from the original file.1340*1341* <p> <b>Usage Examples:</b>1342* Suppose we want to rename a file to "newname", keeping the file in the1343* same directory:1344* <pre>1345* Path source = ...1346* Files.move(source, source.resolveSibling("newname"));1347* </pre>1348* Alternatively, suppose we want to move a file to new directory, keeping1349* the same file name, and replacing any existing file of that name in the1350* directory:1351* <pre>1352* Path source = ...1353* Path newdir = ...1354* Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);1355* </pre>1356*1357* @param source1358* the path to the file to move1359* @param target1360* the path to the target file (may be associated with a different1361* provider to the source path)1362* @param options1363* options specifying how the move should be done1364*1365* @return the path to the target file1366*1367* @throws UnsupportedOperationException1368* if the array contains a copy option that is not supported1369* @throws FileAlreadyExistsException1370* if the target file exists but cannot be replaced because the1371* {@code REPLACE_EXISTING} option is not specified <i>(optional1372* specific exception)</i>1373* @throws DirectoryNotEmptyException1374* the {@code REPLACE_EXISTING} option is specified but the file1375* cannot be replaced because it is a non-empty directory1376* <i>(optional specific exception)</i>1377* @throws AtomicMoveNotSupportedException1378* if the options array contains the {@code ATOMIC_MOVE} option but1379* the file cannot be moved as an atomic file system operation.1380* @throws IOException1381* if an I/O error occurs1382* @throws SecurityException1383* In the case of the default provider, and a security manager is1384* installed, the {@link SecurityManager#checkWrite(String) checkWrite}1385* method is invoked to check write access to both the source and1386* target file.1387*/1388public static Path move(Path source, Path target, CopyOption... options)1389throws IOException1390{1391FileSystemProvider provider = provider(source);1392if (provider(target) == provider) {1393// same provider1394provider.move(source, target, options);1395} else {1396// different providers1397CopyMoveHelper.moveToForeignTarget(source, target, options);1398}1399return target;1400}14011402// -- Miscellenous --14031404/**1405* Reads the target of a symbolic link <i>(optional operation)</i>.1406*1407* <p> If the file system supports <a href="package-summary.html#links">symbolic1408* links</a> then this method is used to read the target of the link, failing1409* if the file is not a symbolic link. The target of the link need not exist.1410* The returned {@code Path} object will be associated with the same file1411* system as {@code link}.1412*1413* @param link1414* the path to the symbolic link1415*1416* @return a {@code Path} object representing the target of the link1417*1418* @throws UnsupportedOperationException1419* if the implementation does not support symbolic links1420* @throws NotLinkException1421* if the target could otherwise not be read because the file1422* is not a symbolic link <i>(optional specific exception)</i>1423* @throws IOException1424* if an I/O error occurs1425* @throws SecurityException1426* In the case of the default provider, and a security manager1427* is installed, it checks that {@code FilePermission} has been1428* granted with the "{@code readlink}" action to read the link.1429*/1430public static Path readSymbolicLink(Path link) throws IOException {1431return provider(link).readSymbolicLink(link);1432}14331434/**1435* Returns the {@link FileStore} representing the file store where a file1436* is located.1437*1438* <p> Once a reference to the {@code FileStore} is obtained it is1439* implementation specific if operations on the returned {@code FileStore},1440* or {@link FileStoreAttributeView} objects obtained from it, continue1441* to depend on the existence of the file. In particular the behavior is not1442* defined for the case that the file is deleted or moved to a different1443* file store.1444*1445* @param path1446* the path to the file1447*1448* @return the file store where the file is stored1449*1450* @throws IOException1451* if an I/O error occurs1452* @throws SecurityException1453* In the case of the default provider, and a security manager is1454* installed, the {@link SecurityManager#checkRead(String) checkRead}1455* method is invoked to check read access to the file, and in1456* addition it checks {@link RuntimePermission}<tt>1457* ("getFileStoreAttributes")</tt>1458*/1459public static FileStore getFileStore(Path path) throws IOException {1460return provider(path).getFileStore(path);1461}14621463/**1464* Tests if two paths locate the same file.1465*1466* <p> If both {@code Path} objects are {@link Path#equals(Object) equal}1467* then this method returns {@code true} without checking if the file exists.1468* If the two {@code Path} objects are associated with different providers1469* then this method returns {@code false}. Otherwise, this method checks if1470* both {@code Path} objects locate the same file, and depending on the1471* implementation, may require to open or access both files.1472*1473* <p> If the file system and files remain static, then this method implements1474* an equivalence relation for non-null {@code Paths}.1475* <ul>1476* <li>It is <i>reflexive</i>: for {@code Path} {@code f},1477* {@code isSameFile(f,f)} should return {@code true}.1478* <li>It is <i>symmetric</i>: for two {@code Paths} {@code f} and {@code g},1479* {@code isSameFile(f,g)} will equal {@code isSameFile(g,f)}.1480* <li>It is <i>transitive</i>: for three {@code Paths}1481* {@code f}, {@code g}, and {@code h}, if {@code isSameFile(f,g)} returns1482* {@code true} and {@code isSameFile(g,h)} returns {@code true}, then1483* {@code isSameFile(f,h)} will return return {@code true}.1484* </ul>1485*1486* @param path1487* one path to the file1488* @param path21489* the other path1490*1491* @return {@code true} if, and only if, the two paths locate the same file1492*1493* @throws IOException1494* if an I/O error occurs1495* @throws SecurityException1496* In the case of the default provider, and a security manager is1497* installed, the {@link SecurityManager#checkRead(String) checkRead}1498* method is invoked to check read access to both files.1499*1500* @see java.nio.file.attribute.BasicFileAttributes#fileKey1501*/1502public static boolean isSameFile(Path path, Path path2) throws IOException {1503return provider(path).isSameFile(path, path2);1504}15051506/**1507* Tells whether or not a file is considered <em>hidden</em>. The exact1508* definition of hidden is platform or provider dependent. On UNIX for1509* example a file is considered to be hidden if its name begins with a1510* period character ('.'). On Windows a file is considered hidden if it1511* isn't a directory and the DOS {@link DosFileAttributes#isHidden hidden}1512* attribute is set.1513*1514* <p> Depending on the implementation this method may require to access1515* the file system to determine if the file is considered hidden.1516*1517* @param path1518* the path to the file to test1519*1520* @return {@code true} if the file is considered hidden1521*1522* @throws IOException1523* if an I/O error occurs1524* @throws SecurityException1525* In the case of the default provider, and a security manager is1526* installed, the {@link SecurityManager#checkRead(String) checkRead}1527* method is invoked to check read access to the file.1528*/1529public static boolean isHidden(Path path) throws IOException {1530return provider(path).isHidden(path);1531}15321533// lazy loading of default and installed file type detectors1534private static class FileTypeDetectors{1535static final FileTypeDetector defaultFileTypeDetector =1536createDefaultFileTypeDetector();1537static final List<FileTypeDetector> installeDetectors =1538loadInstalledDetectors();15391540// creates the default file type detector1541private static FileTypeDetector createDefaultFileTypeDetector() {1542return AccessController1543.doPrivileged(new PrivilegedAction<FileTypeDetector>() {1544@Override public FileTypeDetector run() {1545return sun.nio.fs.DefaultFileTypeDetector.create();1546}});1547}15481549// loads all installed file type detectors1550private static List<FileTypeDetector> loadInstalledDetectors() {1551return AccessController1552.doPrivileged(new PrivilegedAction<List<FileTypeDetector>>() {1553@Override public List<FileTypeDetector> run() {1554List<FileTypeDetector> list = new ArrayList<>();1555ServiceLoader<FileTypeDetector> loader = ServiceLoader1556.load(FileTypeDetector.class, ClassLoader.getSystemClassLoader());1557for (FileTypeDetector detector: loader) {1558list.add(detector);1559}1560return list;1561}});1562}1563}15641565/**1566* Probes the content type of a file.1567*1568* <p> This method uses the installed {@link FileTypeDetector} implementations1569* to probe the given file to determine its content type. Each file type1570* detector's {@link FileTypeDetector#probeContentType probeContentType} is1571* invoked, in turn, to probe the file type. If the file is recognized then1572* the content type is returned. If the file is not recognized by any of the1573* installed file type detectors then a system-default file type detector is1574* invoked to guess the content type.1575*1576* <p> A given invocation of the Java virtual machine maintains a system-wide1577* list of file type detectors. Installed file type detectors are loaded1578* using the service-provider loading facility defined by the {@link ServiceLoader}1579* class. Installed file type detectors are loaded using the system class1580* loader. If the system class loader cannot be found then the extension class1581* loader is used; If the extension class loader cannot be found then the1582* bootstrap class loader is used. File type detectors are typically installed1583* by placing them in a JAR file on the application class path or in the1584* extension directory, the JAR file contains a provider-configuration file1585* named {@code java.nio.file.spi.FileTypeDetector} in the resource directory1586* {@code META-INF/services}, and the file lists one or more fully-qualified1587* names of concrete subclass of {@code FileTypeDetector } that have a zero1588* argument constructor. If the process of locating or instantiating the1589* installed file type detectors fails then an unspecified error is thrown.1590* The ordering that installed providers are located is implementation1591* specific.1592*1593* <p> The return value of this method is the string form of the value of a1594* Multipurpose Internet Mail Extension (MIME) content type as1595* defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045:1596* Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet1597* Message Bodies</i></a>. The string is guaranteed to be parsable according1598* to the grammar in the RFC.1599*1600* @param path1601* the path to the file to probe1602*1603* @return The content type of the file, or {@code null} if the content1604* type cannot be determined1605*1606* @throws IOException1607* if an I/O error occurs1608* @throws SecurityException1609* If a security manager is installed and it denies an unspecified1610* permission required by a file type detector implementation.1611*/1612public static String probeContentType(Path path)1613throws IOException1614{1615// try installed file type detectors1616for (FileTypeDetector detector: FileTypeDetectors.installeDetectors) {1617String result = detector.probeContentType(path);1618if (result != null)1619return result;1620}16211622// fallback to default1623return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path);1624}16251626// -- File Attributes --16271628/**1629* Returns a file attribute view of a given type.1630*1631* <p> A file attribute view provides a read-only or updatable view of a1632* set of file attributes. This method is intended to be used where the file1633* attribute view defines type-safe methods to read or update the file1634* attributes. The {@code type} parameter is the type of the attribute view1635* required and the method returns an instance of that type if supported.1636* The {@link BasicFileAttributeView} type supports access to the basic1637* attributes of a file. Invoking this method to select a file attribute1638* view of that type will always return an instance of that class.1639*1640* <p> The {@code options} array may be used to indicate how symbolic links1641* are handled by the resulting file attribute view for the case that the1642* file is a symbolic link. By default, symbolic links are followed. If the1643* option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then1644* symbolic links are not followed. This option is ignored by implementations1645* that do not support symbolic links.1646*1647* <p> <b>Usage Example:</b>1648* Suppose we want read or set a file's ACL, if supported:1649* <pre>1650* Path path = ...1651* AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);1652* if (view != null) {1653* List<AclEntry> acl = view.getAcl();1654* :1655* }1656* </pre>1657*1658* @param <V>1659* The {@code FileAttributeView} type1660* @param path1661* the path to the file1662* @param type1663* the {@code Class} object corresponding to the file attribute view1664* @param options1665* options indicating how symbolic links are handled1666*1667* @return a file attribute view of the specified type, or {@code null} if1668* the attribute view type is not available1669*/1670public static <V extends FileAttributeView> V getFileAttributeView(Path path,1671Class<V> type,1672LinkOption... options)1673{1674return provider(path).getFileAttributeView(path, type, options);1675}16761677/**1678* Reads a file's attributes as a bulk operation.1679*1680* <p> The {@code type} parameter is the type of the attributes required1681* and this method returns an instance of that type if supported. All1682* implementations support a basic set of file attributes and so invoking1683* this method with a {@code type} parameter of {@code1684* BasicFileAttributes.class} will not throw {@code1685* UnsupportedOperationException}.1686*1687* <p> The {@code options} array may be used to indicate how symbolic links1688* are handled for the case that the file is a symbolic link. By default,1689* symbolic links are followed and the file attribute of the final target1690* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1691* NOFOLLOW_LINKS} is present then symbolic links are not followed.1692*1693* <p> It is implementation specific if all file attributes are read as an1694* atomic operation with respect to other file system operations.1695*1696* <p> <b>Usage Example:</b>1697* Suppose we want to read a file's attributes in bulk:1698* <pre>1699* Path path = ...1700* BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);1701* </pre>1702* Alternatively, suppose we want to read file's POSIX attributes without1703* following symbolic links:1704* <pre>1705* PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS);1706* </pre>1707*1708* @param <A>1709* The {@code BasicFileAttributes} type1710* @param path1711* the path to the file1712* @param type1713* the {@code Class} of the file attributes required1714* to read1715* @param options1716* options indicating how symbolic links are handled1717*1718* @return the file attributes1719*1720* @throws UnsupportedOperationException1721* if an attributes of the given type are not supported1722* @throws IOException1723* if an I/O error occurs1724* @throws SecurityException1725* In the case of the default provider, a security manager is1726* installed, its {@link SecurityManager#checkRead(String) checkRead}1727* method is invoked to check read access to the file. If this1728* method is invoked to read security sensitive attributes then the1729* security manager may be invoke to check for additional permissions.1730*/1731public static <A extends BasicFileAttributes> A readAttributes(Path path,1732Class<A> type,1733LinkOption... options)1734throws IOException1735{1736return provider(path).readAttributes(path, type, options);1737}17381739/**1740* Sets the value of a file attribute.1741*1742* <p> The {@code attribute} parameter identifies the attribute to be set1743* and takes the form:1744* <blockquote>1745* [<i>view-name</i><b>:</b>]<i>attribute-name</i>1746* </blockquote>1747* where square brackets [...] delineate an optional component and the1748* character {@code ':'} stands for itself.1749*1750* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link1751* FileAttributeView} that identifies a set of file attributes. If not1752* specified then it defaults to {@code "basic"}, the name of the file1753* attribute view that identifies the basic set of file attributes common to1754* many file systems. <i>attribute-name</i> is the name of the attribute1755* within the set.1756*1757* <p> The {@code options} array may be used to indicate how symbolic links1758* are handled for the case that the file is a symbolic link. By default,1759* symbolic links are followed and the file attribute of the final target1760* of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS1761* NOFOLLOW_LINKS} is present then symbolic links are not followed.1762*1763* <p> <b>Usage Example:</b>1764* Suppose we want to set the DOS "hidden" attribute:1765* <pre>1766* Path path = ...1767* Files.setAttribute(path, "dos:hidden", true);1768* </pre>1769*1770* @param path1771* the path to the file1772* @param attribute1773* the attribute to set1774* @param value1775* the attribute value1776* @param options1777* options indicating how symbolic links are handled1778*1779* @return the {@code path} parameter1780*1781* @throws UnsupportedOperationException1782* if the attribute view is not available1783* @throws IllegalArgumentException1784* if the attribute name is not specified, or is not recognized, or1785* the attribute value is of the correct type but has an1786* inappropriate value1787* @throws ClassCastException1788* if the attribute value is not of the expected type or is a1789* collection containing elements that are not of the expected1790* type1791* @throws IOException1792* if an I/O error occurs1793* @throws SecurityException1794* In the case of the default provider, and a security manager is1795* installed, its {@link SecurityManager#checkWrite(String) checkWrite}1796* method denies write access to the file. If this method is invoked1797* to set security sensitive attributes then the security manager1798* may be invoked to check for additional permissions.1799*/1800public static Path setAttribute(Path path, String attribute, Object value,1801LinkOption... options)1802throws IOException1803{1804provider(path).setAttribute(path, attribute, value, options);1805return path;1806}18071808/**1809* Reads the value of a file attribute.1810*1811* <p> The {@code attribute} parameter identifies the attribute to be read1812* and takes the form:1813* <blockquote>1814* [<i>view-name</i><b>:</b>]<i>attribute-name</i>1815* </blockquote>1816* where square brackets [...] delineate an optional component and the1817* character {@code ':'} stands for itself.1818*1819* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link1820* FileAttributeView} that identifies a set of file attributes. If not1821* specified then it defaults to {@code "basic"}, the name of the file1822* attribute view that identifies the basic set of file attributes common to1823* many file systems. <i>attribute-name</i> is the name of the attribute.1824*1825* <p> The {@code options} array may be used to indicate how symbolic links1826* are handled for the case that the file is a symbolic link. By default,1827* symbolic links are followed and the file attribute of the final target1828* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1829* NOFOLLOW_LINKS} is present then symbolic links are not followed.1830*1831* <p> <b>Usage Example:</b>1832* Suppose we require the user ID of the file owner on a system that1833* supports a "{@code unix}" view:1834* <pre>1835* Path path = ...1836* int uid = (Integer)Files.getAttribute(path, "unix:uid");1837* </pre>1838*1839* @param path1840* the path to the file1841* @param attribute1842* the attribute to read1843* @param options1844* options indicating how symbolic links are handled1845*1846* @return the attribute value1847*1848* @throws UnsupportedOperationException1849* if the attribute view is not available1850* @throws IllegalArgumentException1851* if the attribute name is not specified or is not recognized1852* @throws IOException1853* if an I/O error occurs1854* @throws SecurityException1855* In the case of the default provider, and a security manager is1856* installed, its {@link SecurityManager#checkRead(String) checkRead}1857* method denies read access to the file. If this method is invoked1858* to read security sensitive attributes then the security manager1859* may be invoked to check for additional permissions.1860*/1861public static Object getAttribute(Path path, String attribute,1862LinkOption... options)1863throws IOException1864{1865// only one attribute should be read1866if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0)1867throw new IllegalArgumentException(attribute);1868Map<String,Object> map = readAttributes(path, attribute, options);1869assert map.size() == 1;1870String name;1871int pos = attribute.indexOf(':');1872if (pos == -1) {1873name = attribute;1874} else {1875name = (pos == attribute.length()) ? "" : attribute.substring(pos+1);1876}1877return map.get(name);1878}18791880/**1881* Reads a set of file attributes as a bulk operation.1882*1883* <p> The {@code attributes} parameter identifies the attributes to be read1884* and takes the form:1885* <blockquote>1886* [<i>view-name</i><b>:</b>]<i>attribute-list</i>1887* </blockquote>1888* where square brackets [...] delineate an optional component and the1889* character {@code ':'} stands for itself.1890*1891* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link1892* FileAttributeView} that identifies a set of file attributes. If not1893* specified then it defaults to {@code "basic"}, the name of the file1894* attribute view that identifies the basic set of file attributes common to1895* many file systems.1896*1897* <p> The <i>attribute-list</i> component is a comma separated list of1898* zero or more names of attributes to read. If the list contains the value1899* {@code "*"} then all attributes are read. Attributes that are not supported1900* are ignored and will not be present in the returned map. It is1901* implementation specific if all attributes are read as an atomic operation1902* with respect to other file system operations.1903*1904* <p> The following examples demonstrate possible values for the {@code1905* attributes} parameter:1906*1907* <blockquote>1908* <table border="0" summary="Possible values">1909* <tr>1910* <td> {@code "*"} </td>1911* <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td>1912* </tr>1913* <tr>1914* <td> {@code "size,lastModifiedTime,lastAccessTime"} </td>1915* <td> Reads the file size, last modified time, and last access time1916* attributes. </td>1917* </tr>1918* <tr>1919* <td> {@code "posix:*"} </td>1920* <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td>1921* </tr>1922* <tr>1923* <td> {@code "posix:permissions,owner,size"} </td>1924* <td> Reads the POSX file permissions, owner, and file size. </td>1925* </tr>1926* </table>1927* </blockquote>1928*1929* <p> The {@code options} array may be used to indicate how symbolic links1930* are handled for the case that the file is a symbolic link. By default,1931* symbolic links are followed and the file attribute of the final target1932* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1933* NOFOLLOW_LINKS} is present then symbolic links are not followed.1934*1935* @param path1936* the path to the file1937* @param attributes1938* the attributes to read1939* @param options1940* options indicating how symbolic links are handled1941*1942* @return a map of the attributes returned; The map's keys are the1943* attribute names, its values are the attribute values1944*1945* @throws UnsupportedOperationException1946* if the attribute view is not available1947* @throws IllegalArgumentException1948* if no attributes are specified or an unrecognized attributes is1949* specified1950* @throws IOException1951* if an I/O error occurs1952* @throws SecurityException1953* In the case of the default provider, and a security manager is1954* installed, its {@link SecurityManager#checkRead(String) checkRead}1955* method denies read access to the file. If this method is invoked1956* to read security sensitive attributes then the security manager1957* may be invoke to check for additional permissions.1958*/1959public static Map<String,Object> readAttributes(Path path, String attributes,1960LinkOption... options)1961throws IOException1962{1963return provider(path).readAttributes(path, attributes, options);1964}19651966/**1967* Returns a file's POSIX file permissions.1968*1969* <p> The {@code path} parameter is associated with a {@code FileSystem}1970* that supports the {@link PosixFileAttributeView}. This attribute view1971* provides access to file attributes commonly associated with files on file1972* systems used by operating systems that implement the Portable Operating1973* System Interface (POSIX) family of standards.1974*1975* <p> The {@code options} array may be used to indicate how symbolic links1976* are handled for the case that the file is a symbolic link. By default,1977* symbolic links are followed and the file attribute of the final target1978* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1979* NOFOLLOW_LINKS} is present then symbolic links are not followed.1980*1981* @param path1982* the path to the file1983* @param options1984* options indicating how symbolic links are handled1985*1986* @return the file permissions1987*1988* @throws UnsupportedOperationException1989* if the associated file system does not support the {@code1990* PosixFileAttributeView}1991* @throws IOException1992* if an I/O error occurs1993* @throws SecurityException1994* In the case of the default provider, a security manager is1995* installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>1996* or its {@link SecurityManager#checkRead(String) checkRead} method1997* denies read access to the file.1998*/1999public static Set<PosixFilePermission> getPosixFilePermissions(Path path,2000LinkOption... options)2001throws IOException2002{2003return readAttributes(path, PosixFileAttributes.class, options).permissions();2004}20052006/**2007* Sets a file's POSIX permissions.2008*2009* <p> The {@code path} parameter is associated with a {@code FileSystem}2010* that supports the {@link PosixFileAttributeView}. This attribute view2011* provides access to file attributes commonly associated with files on file2012* systems used by operating systems that implement the Portable Operating2013* System Interface (POSIX) family of standards.2014*2015* @param path2016* The path to the file2017* @param perms2018* The new set of permissions2019*2020* @return The path2021*2022* @throws UnsupportedOperationException2023* if the associated file system does not support the {@code2024* PosixFileAttributeView}2025* @throws ClassCastException2026* if the sets contains elements that are not of type {@code2027* PosixFilePermission}2028* @throws IOException2029* if an I/O error occurs2030* @throws SecurityException2031* In the case of the default provider, and a security manager is2032* installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>2033* or its {@link SecurityManager#checkWrite(String) checkWrite}2034* method denies write access to the file.2035*/2036public static Path setPosixFilePermissions(Path path,2037Set<PosixFilePermission> perms)2038throws IOException2039{2040PosixFileAttributeView view =2041getFileAttributeView(path, PosixFileAttributeView.class);2042if (view == null)2043throw new UnsupportedOperationException();2044view.setPermissions(perms);2045return path;2046}20472048/**2049* Returns the owner of a file.2050*2051* <p> The {@code path} parameter is associated with a file system that2052* supports {@link FileOwnerAttributeView}. This file attribute view provides2053* access to a file attribute that is the owner of the file.2054*2055* @param path2056* The path to the file2057* @param options2058* options indicating how symbolic links are handled2059*2060* @return A user principal representing the owner of the file2061*2062* @throws UnsupportedOperationException2063* if the associated file system does not support the {@code2064* FileOwnerAttributeView}2065* @throws IOException2066* if an I/O error occurs2067* @throws SecurityException2068* In the case of the default provider, and a security manager is2069* installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>2070* or its {@link SecurityManager#checkRead(String) checkRead} method2071* denies read access to the file.2072*/2073public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException {2074FileOwnerAttributeView view =2075getFileAttributeView(path, FileOwnerAttributeView.class, options);2076if (view == null)2077throw new UnsupportedOperationException();2078return view.getOwner();2079}20802081/**2082* Updates the file owner.2083*2084* <p> The {@code path} parameter is associated with a file system that2085* supports {@link FileOwnerAttributeView}. This file attribute view provides2086* access to a file attribute that is the owner of the file.2087*2088* <p> <b>Usage Example:</b>2089* Suppose we want to make "joe" the owner of a file:2090* <pre>2091* Path path = ...2092* UserPrincipalLookupService lookupService =2093* provider(path).getUserPrincipalLookupService();2094* UserPrincipal joe = lookupService.lookupPrincipalByName("joe");2095* Files.setOwner(path, joe);2096* </pre>2097*2098* @param path2099* The path to the file2100* @param owner2101* The new file owner2102*2103* @return The path2104*2105* @throws UnsupportedOperationException2106* if the associated file system does not support the {@code2107* FileOwnerAttributeView}2108* @throws IOException2109* if an I/O error occurs2110* @throws SecurityException2111* In the case of the default provider, and a security manager is2112* installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>2113* or its {@link SecurityManager#checkWrite(String) checkWrite}2114* method denies write access to the file.2115*2116* @see FileSystem#getUserPrincipalLookupService2117* @see java.nio.file.attribute.UserPrincipalLookupService2118*/2119public static Path setOwner(Path path, UserPrincipal owner)2120throws IOException2121{2122FileOwnerAttributeView view =2123getFileAttributeView(path, FileOwnerAttributeView.class);2124if (view == null)2125throw new UnsupportedOperationException();2126view.setOwner(owner);2127return path;2128}21292130/**2131* Tests whether a file is a symbolic link.2132*2133* <p> Where it is required to distinguish an I/O exception from the case2134* that the file is not a symbolic link then the file attributes can be2135* read with the {@link #readAttributes(Path,Class,LinkOption[])2136* readAttributes} method and the file type tested with the {@link2137* BasicFileAttributes#isSymbolicLink} method.2138*2139* @param path The path to the file2140*2141* @return {@code true} if the file is a symbolic link; {@code false} if2142* the file does not exist, is not a symbolic link, or it cannot2143* be determined if the file is a symbolic link or not.2144*2145* @throws SecurityException2146* In the case of the default provider, and a security manager is2147* installed, its {@link SecurityManager#checkRead(String) checkRead}2148* method denies read access to the file.2149*/2150public static boolean isSymbolicLink(Path path) {2151try {2152return readAttributes(path,2153BasicFileAttributes.class,2154LinkOption.NOFOLLOW_LINKS).isSymbolicLink();2155} catch (IOException ioe) {2156return false;2157}2158}21592160/**2161* Tests whether a file is a directory.2162*2163* <p> The {@code options} array may be used to indicate how symbolic links2164* are handled for the case that the file is a symbolic link. By default,2165* symbolic links are followed and the file attribute of the final target2166* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2167* NOFOLLOW_LINKS} is present then symbolic links are not followed.2168*2169* <p> Where it is required to distinguish an I/O exception from the case2170* that the file is not a directory then the file attributes can be2171* read with the {@link #readAttributes(Path,Class,LinkOption[])2172* readAttributes} method and the file type tested with the {@link2173* BasicFileAttributes#isDirectory} method.2174*2175* @param path2176* the path to the file to test2177* @param options2178* options indicating how symbolic links are handled2179*2180* @return {@code true} if the file is a directory; {@code false} if2181* the file does not exist, is not a directory, or it cannot2182* be determined if the file is a directory or not.2183*2184* @throws SecurityException2185* In the case of the default provider, and a security manager is2186* installed, its {@link SecurityManager#checkRead(String) checkRead}2187* method denies read access to the file.2188*/2189public static boolean isDirectory(Path path, LinkOption... options) {2190try {2191return readAttributes(path, BasicFileAttributes.class, options).isDirectory();2192} catch (IOException ioe) {2193return false;2194}2195}21962197/**2198* Tests whether a file is a regular file with opaque content.2199*2200* <p> The {@code options} array may be used to indicate how symbolic links2201* are handled for the case that the file is a symbolic link. By default,2202* symbolic links are followed and the file attribute of the final target2203* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2204* NOFOLLOW_LINKS} is present then symbolic links are not followed.2205*2206* <p> Where it is required to distinguish an I/O exception from the case2207* that the file is not a regular file then the file attributes can be2208* read with the {@link #readAttributes(Path,Class,LinkOption[])2209* readAttributes} method and the file type tested with the {@link2210* BasicFileAttributes#isRegularFile} method.2211*2212* @param path2213* the path to the file2214* @param options2215* options indicating how symbolic links are handled2216*2217* @return {@code true} if the file is a regular file; {@code false} if2218* the file does not exist, is not a regular file, or it2219* cannot be determined if the file is a regular file or not.2220*2221* @throws SecurityException2222* In the case of the default provider, and a security manager is2223* installed, its {@link SecurityManager#checkRead(String) checkRead}2224* method denies read access to the file.2225*/2226public static boolean isRegularFile(Path path, LinkOption... options) {2227try {2228return readAttributes(path, BasicFileAttributes.class, options).isRegularFile();2229} catch (IOException ioe) {2230return false;2231}2232}22332234/**2235* Returns a file's last modified time.2236*2237* <p> The {@code options} array may be used to indicate how symbolic links2238* are handled for the case that the file is a symbolic link. By default,2239* symbolic links are followed and the file attribute of the final target2240* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2241* NOFOLLOW_LINKS} is present then symbolic links are not followed.2242*2243* @param path2244* the path to the file2245* @param options2246* options indicating how symbolic links are handled2247*2248* @return a {@code FileTime} representing the time the file was last2249* modified, or an implementation specific default when a time2250* stamp to indicate the time of last modification is not supported2251* by the file system2252*2253* @throws IOException2254* if an I/O error occurs2255* @throws SecurityException2256* In the case of the default provider, and a security manager is2257* installed, its {@link SecurityManager#checkRead(String) checkRead}2258* method denies read access to the file.2259*2260* @see BasicFileAttributes#lastModifiedTime2261*/2262public static FileTime getLastModifiedTime(Path path, LinkOption... options)2263throws IOException2264{2265return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime();2266}22672268/**2269* Updates a file's last modified time attribute. The file time is converted2270* to the epoch and precision supported by the file system. Converting from2271* finer to coarser granularities result in precision loss. The behavior of2272* this method when attempting to set the last modified time when it is not2273* supported by the file system or is outside the range supported by the2274* underlying file store is not defined. It may or not fail by throwing an2275* {@code IOException}.2276*2277* <p> <b>Usage Example:</b>2278* Suppose we want to set the last modified time to the current time:2279* <pre>2280* Path path = ...2281* FileTime now = FileTime.fromMillis(System.currentTimeMillis());2282* Files.setLastModifiedTime(path, now);2283* </pre>2284*2285* @param path2286* the path to the file2287* @param time2288* the new last modified time2289*2290* @return the path2291*2292* @throws IOException2293* if an I/O error occurs2294* @throws SecurityException2295* In the case of the default provider, the security manager's {@link2296* SecurityManager#checkWrite(String) checkWrite} method is invoked2297* to check write access to file2298*2299* @see BasicFileAttributeView#setTimes2300*/2301public static Path setLastModifiedTime(Path path, FileTime time)2302throws IOException2303{2304getFileAttributeView(path, BasicFileAttributeView.class)2305.setTimes(time, null, null);2306return path;2307}23082309/**2310* Returns the size of a file (in bytes). The size may differ from the2311* actual size on the file system due to compression, support for sparse2312* files, or other reasons. The size of files that are not {@link2313* #isRegularFile regular} files is implementation specific and2314* therefore unspecified.2315*2316* @param path2317* the path to the file2318*2319* @return the file size, in bytes2320*2321* @throws IOException2322* if an I/O error occurs2323* @throws SecurityException2324* In the case of the default provider, and a security manager is2325* installed, its {@link SecurityManager#checkRead(String) checkRead}2326* method denies read access to the file.2327*2328* @see BasicFileAttributes#size2329*/2330public static long size(Path path) throws IOException {2331return readAttributes(path, BasicFileAttributes.class).size();2332}23332334// -- Accessibility --23352336/**2337* Returns {@code false} if NOFOLLOW_LINKS is present.2338*/2339private static boolean followLinks(LinkOption... options) {2340boolean followLinks = true;2341for (LinkOption opt: options) {2342if (opt == LinkOption.NOFOLLOW_LINKS) {2343followLinks = false;2344continue;2345}2346if (opt == null)2347throw new NullPointerException();2348throw new AssertionError("Should not get here");2349}2350return followLinks;2351}23522353/**2354* Tests whether a file exists.2355*2356* <p> The {@code options} parameter may be used to indicate how symbolic links2357* are handled for the case that the file is a symbolic link. By default,2358* symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS2359* NOFOLLOW_LINKS} is present then symbolic links are not followed.2360*2361* <p> Note that the result of this method is immediately outdated. If this2362* method indicates the file exists then there is no guarantee that a2363* subsequence access will succeed. Care should be taken when using this2364* method in security sensitive applications.2365*2366* @param path2367* the path to the file to test2368* @param options2369* options indicating how symbolic links are handled2370* .2371* @return {@code true} if the file exists; {@code false} if the file does2372* not exist or its existence cannot be determined.2373*2374* @throws SecurityException2375* In the case of the default provider, the {@link2376* SecurityManager#checkRead(String)} is invoked to check2377* read access to the file.2378*2379* @see #notExists2380*/2381public static boolean exists(Path path, LinkOption... options) {2382try {2383if (followLinks(options)) {2384provider(path).checkAccess(path);2385} else {2386// attempt to read attributes without following links2387readAttributes(path, BasicFileAttributes.class,2388LinkOption.NOFOLLOW_LINKS);2389}2390// file exists2391return true;2392} catch (IOException x) {2393// does not exist or unable to determine if file exists2394return false;2395}23962397}23982399/**2400* Tests whether the file located by this path does not exist. This method2401* is intended for cases where it is required to take action when it can be2402* confirmed that a file does not exist.2403*2404* <p> The {@code options} parameter may be used to indicate how symbolic links2405* are handled for the case that the file is a symbolic link. By default,2406* symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS2407* NOFOLLOW_LINKS} is present then symbolic links are not followed.2408*2409* <p> Note that this method is not the complement of the {@link #exists2410* exists} method. Where it is not possible to determine if a file exists2411* or not then both methods return {@code false}. As with the {@code exists}2412* method, the result of this method is immediately outdated. If this2413* method indicates the file does exist then there is no guarantee that a2414* subsequence attempt to create the file will succeed. Care should be taken2415* when using this method in security sensitive applications.2416*2417* @param path2418* the path to the file to test2419* @param options2420* options indicating how symbolic links are handled2421*2422* @return {@code true} if the file does not exist; {@code false} if the2423* file exists or its existence cannot be determined2424*2425* @throws SecurityException2426* In the case of the default provider, the {@link2427* SecurityManager#checkRead(String)} is invoked to check2428* read access to the file.2429*/2430public static boolean notExists(Path path, LinkOption... options) {2431try {2432if (followLinks(options)) {2433provider(path).checkAccess(path);2434} else {2435// attempt to read attributes without following links2436readAttributes(path, BasicFileAttributes.class,2437LinkOption.NOFOLLOW_LINKS);2438}2439// file exists2440return false;2441} catch (NoSuchFileException x) {2442// file confirmed not to exist2443return true;2444} catch (IOException x) {2445return false;2446}2447}24482449/**2450* Used by isReadbale, isWritable, isExecutable to test access to a file.2451*/2452private static boolean isAccessible(Path path, AccessMode... modes) {2453try {2454provider(path).checkAccess(path, modes);2455return true;2456} catch (IOException x) {2457return false;2458}2459}24602461/**2462* Tests whether a file is readable. This method checks that a file exists2463* and that this Java virtual machine has appropriate privileges that would2464* allow it open the file for reading. Depending on the implementation, this2465* method may require to read file permissions, access control lists, or2466* other file attributes in order to check the effective access to the file.2467* Consequently, this method may not be atomic with respect to other file2468* system operations.2469*2470* <p> Note that the result of this method is immediately outdated, there is2471* no guarantee that a subsequent attempt to open the file for reading will2472* succeed (or even that it will access the same file). Care should be taken2473* when using this method in security sensitive applications.2474*2475* @param path2476* the path to the file to check2477*2478* @return {@code true} if the file exists and is readable; {@code false}2479* if the file does not exist, read access would be denied because2480* the Java virtual machine has insufficient privileges, or access2481* cannot be determined2482*2483* @throws SecurityException2484* In the case of the default provider, and a security manager is2485* installed, the {@link SecurityManager#checkRead(String) checkRead}2486* is invoked to check read access to the file.2487*/2488public static boolean isReadable(Path path) {2489return isAccessible(path, AccessMode.READ);2490}24912492/**2493* Tests whether a file is writable. This method checks that a file exists2494* and that this Java virtual machine has appropriate privileges that would2495* allow it open the file for writing. Depending on the implementation, this2496* method may require to read file permissions, access control lists, or2497* other file attributes in order to check the effective access to the file.2498* Consequently, this method may not be atomic with respect to other file2499* system operations.2500*2501* <p> Note that result of this method is immediately outdated, there is no2502* guarantee that a subsequent attempt to open the file for writing will2503* succeed (or even that it will access the same file). Care should be taken2504* when using this method in security sensitive applications.2505*2506* @param path2507* the path to the file to check2508*2509* @return {@code true} if the file exists and is writable; {@code false}2510* if the file does not exist, write access would be denied because2511* the Java virtual machine has insufficient privileges, or access2512* cannot be determined2513*2514* @throws SecurityException2515* In the case of the default provider, and a security manager is2516* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2517* is invoked to check write access to the file.2518*/2519public static boolean isWritable(Path path) {2520return isAccessible(path, AccessMode.WRITE);2521}25222523/**2524* Tests whether a file is executable. This method checks that a file exists2525* and that this Java virtual machine has appropriate privileges to {@link2526* Runtime#exec execute} the file. The semantics may differ when checking2527* access to a directory. For example, on UNIX systems, checking for2528* execute access checks that the Java virtual machine has permission to2529* search the directory in order to access file or subdirectories.2530*2531* <p> Depending on the implementation, this method may require to read file2532* permissions, access control lists, or other file attributes in order to2533* check the effective access to the file. Consequently, this method may not2534* be atomic with respect to other file system operations.2535*2536* <p> Note that the result of this method is immediately outdated, there is2537* no guarantee that a subsequent attempt to execute the file will succeed2538* (or even that it will access the same file). Care should be taken when2539* using this method in security sensitive applications.2540*2541* @param path2542* the path to the file to check2543*2544* @return {@code true} if the file exists and is executable; {@code false}2545* if the file does not exist, execute access would be denied because2546* the Java virtual machine has insufficient privileges, or access2547* cannot be determined2548*2549* @throws SecurityException2550* In the case of the default provider, and a security manager is2551* installed, the {@link SecurityManager#checkExec(String)2552* checkExec} is invoked to check execute access to the file.2553*/2554public static boolean isExecutable(Path path) {2555return isAccessible(path, AccessMode.EXECUTE);2556}25572558// -- Recursive operations --25592560/**2561* Walks a file tree.2562*2563* <p> This method walks a file tree rooted at a given starting file. The2564* file tree traversal is <em>depth-first</em> with the given {@link2565* FileVisitor} invoked for each file encountered. File tree traversal2566* completes when all accessible files in the tree have been visited, or a2567* visit method returns a result of {@link FileVisitResult#TERMINATE2568* TERMINATE}. Where a visit method terminates due an {@code IOException},2569* an uncaught error, or runtime exception, then the traversal is terminated2570* and the error or exception is propagated to the caller of this method.2571*2572* <p> For each file encountered this method attempts to read its {@link2573* java.nio.file.attribute.BasicFileAttributes}. If the file is not a2574* directory then the {@link FileVisitor#visitFile visitFile} method is2575* invoked with the file attributes. If the file attributes cannot be read,2576* due to an I/O exception, then the {@link FileVisitor#visitFileFailed2577* visitFileFailed} method is invoked with the I/O exception.2578*2579* <p> Where the file is a directory, and the directory could not be opened,2580* then the {@code visitFileFailed} method is invoked with the I/O exception,2581* after which, the file tree walk continues, by default, at the next2582* <em>sibling</em> of the directory.2583*2584* <p> Where the directory is opened successfully, then the entries in the2585* directory, and their <em>descendants</em> are visited. When all entries2586* have been visited, or an I/O error occurs during iteration of the2587* directory, then the directory is closed and the visitor's {@link2588* FileVisitor#postVisitDirectory postVisitDirectory} method is invoked.2589* The file tree walk then continues, by default, at the next <em>sibling</em>2590* of the directory.2591*2592* <p> By default, symbolic links are not automatically followed by this2593* method. If the {@code options} parameter contains the {@link2594* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are2595* followed. When following links, and the attributes of the target cannot2596* be read, then this method attempts to get the {@code BasicFileAttributes}2597* of the link. If they can be read then the {@code visitFile} method is2598* invoked with the attributes of the link (otherwise the {@code visitFileFailed}2599* method is invoked as specified above).2600*2601* <p> If the {@code options} parameter contains the {@link2602* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps2603* track of directories visited so that cycles can be detected. A cycle2604* arises when there is an entry in a directory that is an ancestor of the2605* directory. Cycle detection is done by recording the {@link2606* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,2607* or if file keys are not available, by invoking the {@link #isSameFile2608* isSameFile} method to test if a directory is the same file as an2609* ancestor. When a cycle is detected it is treated as an I/O error, and the2610* {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with2611* an instance of {@link FileSystemLoopException}.2612*2613* <p> The {@code maxDepth} parameter is the maximum number of levels of2614* directories to visit. A value of {@code 0} means that only the starting2615* file is visited, unless denied by the security manager. A value of2616* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all2617* levels should be visited. The {@code visitFile} method is invoked for all2618* files, including directories, encountered at {@code maxDepth}, unless the2619* basic file attributes cannot be read, in which case the {@code2620* visitFileFailed} method is invoked.2621*2622* <p> If a visitor returns a result of {@code null} then {@code2623* NullPointerException} is thrown.2624*2625* <p> When a security manager is installed and it denies access to a file2626* (or directory), then it is ignored and the visitor is not invoked for2627* that file (or directory).2628*2629* @param start2630* the starting file2631* @param options2632* options to configure the traversal2633* @param maxDepth2634* the maximum number of directory levels to visit2635* @param visitor2636* the file visitor to invoke for each file2637*2638* @return the starting file2639*2640* @throws IllegalArgumentException2641* if the {@code maxDepth} parameter is negative2642* @throws SecurityException2643* If the security manager denies access to the starting file.2644* In the case of the default provider, the {@link2645* SecurityManager#checkRead(String) checkRead} method is invoked2646* to check read access to the directory.2647* @throws IOException2648* if an I/O error is thrown by a visitor method2649*/2650public static Path walkFileTree(Path start,2651Set<FileVisitOption> options,2652int maxDepth,2653FileVisitor<? super Path> visitor)2654throws IOException2655{2656/**2657* Create a FileTreeWalker to walk the file tree, invoking the visitor2658* for each event.2659*/2660try (FileTreeWalker walker = new FileTreeWalker(options, maxDepth)) {2661FileTreeWalker.Event ev = walker.walk(start);2662do {2663FileVisitResult result;2664switch (ev.type()) {2665case ENTRY :2666IOException ioe = ev.ioeException();2667if (ioe == null) {2668assert ev.attributes() != null;2669result = visitor.visitFile(ev.file(), ev.attributes());2670} else {2671result = visitor.visitFileFailed(ev.file(), ioe);2672}2673break;26742675case START_DIRECTORY :2676result = visitor.preVisitDirectory(ev.file(), ev.attributes());26772678// if SKIP_SIBLINGS and SKIP_SUBTREE is returned then2679// there shouldn't be any more events for the current2680// directory.2681if (result == FileVisitResult.SKIP_SUBTREE ||2682result == FileVisitResult.SKIP_SIBLINGS)2683walker.pop();2684break;26852686case END_DIRECTORY :2687result = visitor.postVisitDirectory(ev.file(), ev.ioeException());26882689// SKIP_SIBLINGS is a no-op for postVisitDirectory2690if (result == FileVisitResult.SKIP_SIBLINGS)2691result = FileVisitResult.CONTINUE;2692break;26932694default :2695throw new AssertionError("Should not get here");2696}26972698if (Objects.requireNonNull(result) != FileVisitResult.CONTINUE) {2699if (result == FileVisitResult.TERMINATE) {2700break;2701} else if (result == FileVisitResult.SKIP_SIBLINGS) {2702walker.skipRemainingSiblings();2703}2704}2705ev = walker.next();2706} while (ev != null);2707}27082709return start;2710}27112712/**2713* Walks a file tree.2714*2715* <p> This method works as if invoking it were equivalent to evaluating the2716* expression:2717* <blockquote><pre>2718* walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)2719* </pre></blockquote>2720* In other words, it does not follow symbolic links, and visits all levels2721* of the file tree.2722*2723* @param start2724* the starting file2725* @param visitor2726* the file visitor to invoke for each file2727*2728* @return the starting file2729*2730* @throws SecurityException2731* If the security manager denies access to the starting file.2732* In the case of the default provider, the {@link2733* SecurityManager#checkRead(String) checkRead} method is invoked2734* to check read access to the directory.2735* @throws IOException2736* if an I/O error is thrown by a visitor method2737*/2738public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)2739throws IOException2740{2741return walkFileTree(start,2742EnumSet.noneOf(FileVisitOption.class),2743Integer.MAX_VALUE,2744visitor);2745}274627472748// -- Utility methods for simple usages --27492750// buffer size used for reading and writing2751private static final int BUFFER_SIZE = 8192;27522753/**2754* Opens a file for reading, returning a {@code BufferedReader} that may be2755* used to read text from the file in an efficient manner. Bytes from the2756* file are decoded into characters using the specified charset. Reading2757* commences at the beginning of the file.2758*2759* <p> The {@code Reader} methods that read from the file throw {@code2760* IOException} if a malformed or unmappable byte sequence is read.2761*2762* @param path2763* the path to the file2764* @param cs2765* the charset to use for decoding2766*2767* @return a new buffered reader, with default buffer size, to read text2768* from the file2769*2770* @throws IOException2771* if an I/O error occurs opening the file2772* @throws SecurityException2773* In the case of the default provider, and a security manager is2774* installed, the {@link SecurityManager#checkRead(String) checkRead}2775* method is invoked to check read access to the file.2776*2777* @see #readAllLines2778*/2779public static BufferedReader newBufferedReader(Path path, Charset cs)2780throws IOException2781{2782CharsetDecoder decoder = cs.newDecoder();2783Reader reader = new InputStreamReader(newInputStream(path), decoder);2784return new BufferedReader(reader);2785}27862787/**2788* Opens a file for reading, returning a {@code BufferedReader} to read text2789* from the file in an efficient manner. Bytes from the file are decoded into2790* characters using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset2791* charset}.2792*2793* <p> This method works as if invoking it were equivalent to evaluating the2794* expression:2795* <pre>{@code2796* Files.newBufferedReader(path, StandardCharsets.UTF_8)2797* }</pre>2798*2799* @param path2800* the path to the file2801*2802* @return a new buffered reader, with default buffer size, to read text2803* from the file2804*2805* @throws IOException2806* if an I/O error occurs opening the file2807* @throws SecurityException2808* In the case of the default provider, and a security manager is2809* installed, the {@link SecurityManager#checkRead(String) checkRead}2810* method is invoked to check read access to the file.2811*2812* @since 1.82813*/2814public static BufferedReader newBufferedReader(Path path) throws IOException {2815return newBufferedReader(path, StandardCharsets.UTF_8);2816}28172818/**2819* Opens or creates a file for writing, returning a {@code BufferedWriter}2820* that may be used to write text to the file in an efficient manner.2821* The {@code options} parameter specifies how the the file is created or2822* opened. If no options are present then this method works as if the {@link2823* StandardOpenOption#CREATE CREATE}, {@link2824* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link2825* StandardOpenOption#WRITE WRITE} options are present. In other words, it2826* opens the file for writing, creating the file if it doesn't exist, or2827* initially truncating an existing {@link #isRegularFile regular-file} to2828* a size of {@code 0} if it exists.2829*2830* <p> The {@code Writer} methods to write text throw {@code IOException}2831* if the text cannot be encoded using the specified charset.2832*2833* @param path2834* the path to the file2835* @param cs2836* the charset to use for encoding2837* @param options2838* options specifying how the file is opened2839*2840* @return a new buffered writer, with default buffer size, to write text2841* to the file2842*2843* @throws IOException2844* if an I/O error occurs opening or creating the file2845* @throws UnsupportedOperationException2846* if an unsupported option is specified2847* @throws SecurityException2848* In the case of the default provider, and a security manager is2849* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2850* method is invoked to check write access to the file.2851*2852* @see #write(Path,Iterable,Charset,OpenOption[])2853*/2854public static BufferedWriter newBufferedWriter(Path path, Charset cs,2855OpenOption... options)2856throws IOException2857{2858CharsetEncoder encoder = cs.newEncoder();2859Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder);2860return new BufferedWriter(writer);2861}28622863/**2864* Opens or creates a file for writing, returning a {@code BufferedWriter}2865* to write text to the file in an efficient manner. The text is encoded2866* into bytes for writing using the {@link StandardCharsets#UTF_8 UTF-8}2867* {@link Charset charset}.2868*2869* <p> This method works as if invoking it were equivalent to evaluating the2870* expression:2871* <pre>{@code2872* Files.newBufferedWriter(path, StandardCharsets.UTF_8, options)2873* }</pre>2874*2875* @param path2876* the path to the file2877* @param options2878* options specifying how the file is opened2879*2880* @return a new buffered writer, with default buffer size, to write text2881* to the file2882*2883* @throws IOException2884* if an I/O error occurs opening or creating the file2885* @throws UnsupportedOperationException2886* if an unsupported option is specified2887* @throws SecurityException2888* In the case of the default provider, and a security manager is2889* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2890* method is invoked to check write access to the file.2891*2892* @since 1.82893*/2894public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException {2895return newBufferedWriter(path, StandardCharsets.UTF_8, options);2896}28972898/**2899* Reads all bytes from an input stream and writes them to an output stream.2900*/2901private static long copy(InputStream source, OutputStream sink)2902throws IOException2903{2904long nread = 0L;2905byte[] buf = new byte[BUFFER_SIZE];2906int n;2907while ((n = source.read(buf)) > 0) {2908sink.write(buf, 0, n);2909nread += n;2910}2911return nread;2912}29132914/**2915* Copies all bytes from an input stream to a file. On return, the input2916* stream will be at end of stream.2917*2918* <p> By default, the copy fails if the target file already exists or is a2919* symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING2920* REPLACE_EXISTING} option is specified, and the target file already exists,2921* then it is replaced if it is not a non-empty directory. If the target2922* file exists and is a symbolic link, then the symbolic link is replaced.2923* In this release, the {@code REPLACE_EXISTING} option is the only option2924* required to be supported by this method. Additional options may be2925* supported in future releases.2926*2927* <p> If an I/O error occurs reading from the input stream or writing to2928* the file, then it may do so after the target file has been created and2929* after some bytes have been read or written. Consequently the input2930* stream may not be at end of stream and may be in an inconsistent state.2931* It is strongly recommended that the input stream be promptly closed if an2932* I/O error occurs.2933*2934* <p> This method may block indefinitely reading from the input stream (or2935* writing to the file). The behavior for the case that the input stream is2936* <i>asynchronously closed</i> or the thread interrupted during the copy is2937* highly input stream and file system provider specific and therefore not2938* specified.2939*2940* <p> <b>Usage example</b>: Suppose we want to capture a web page and save2941* it to a file:2942* <pre>2943* Path path = ...2944* URI u = URI.create("http://java.sun.com/");2945* try (InputStream in = u.toURL().openStream()) {2946* Files.copy(in, path);2947* }2948* </pre>2949*2950* @param in2951* the input stream to read from2952* @param target2953* the path to the file2954* @param options2955* options specifying how the copy should be done2956*2957* @return the number of bytes read or written2958*2959* @throws IOException2960* if an I/O error occurs when reading or writing2961* @throws FileAlreadyExistsException2962* if the target file exists but cannot be replaced because the2963* {@code REPLACE_EXISTING} option is not specified <i>(optional2964* specific exception)</i>2965* @throws DirectoryNotEmptyException2966* the {@code REPLACE_EXISTING} option is specified but the file2967* cannot be replaced because it is a non-empty directory2968* <i>(optional specific exception)</i> *2969* @throws UnsupportedOperationException2970* if {@code options} contains a copy option that is not supported2971* @throws SecurityException2972* In the case of the default provider, and a security manager is2973* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2974* method is invoked to check write access to the file. Where the2975* {@code REPLACE_EXISTING} option is specified, the security2976* manager's {@link SecurityManager#checkDelete(String) checkDelete}2977* method is invoked to check that an existing file can be deleted.2978*/2979public static long copy(InputStream in, Path target, CopyOption... options)2980throws IOException2981{2982// ensure not null before opening file2983Objects.requireNonNull(in);29842985// check for REPLACE_EXISTING2986boolean replaceExisting = false;2987for (CopyOption opt: options) {2988if (opt == StandardCopyOption.REPLACE_EXISTING) {2989replaceExisting = true;2990} else {2991if (opt == null) {2992throw new NullPointerException("options contains 'null'");2993} else {2994throw new UnsupportedOperationException(opt + " not supported");2995}2996}2997}29982999// attempt to delete an existing file3000SecurityException se = null;3001if (replaceExisting) {3002try {3003deleteIfExists(target);3004} catch (SecurityException x) {3005se = x;3006}3007}30083009// attempt to create target file. If it fails with3010// FileAlreadyExistsException then it may be because the security3011// manager prevented us from deleting the file, in which case we just3012// throw the SecurityException.3013OutputStream ostream;3014try {3015ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,3016StandardOpenOption.WRITE);3017} catch (FileAlreadyExistsException x) {3018if (se != null)3019throw se;3020// someone else won the race and created the file3021throw x;3022}30233024// do the copy3025try (OutputStream out = ostream) {3026return copy(in, out);3027}3028}30293030/**3031* Copies all bytes from a file to an output stream.3032*3033* <p> If an I/O error occurs reading from the file or writing to the output3034* stream, then it may do so after some bytes have been read or written.3035* Consequently the output stream may be in an inconsistent state. It is3036* strongly recommended that the output stream be promptly closed if an I/O3037* error occurs.3038*3039* <p> This method may block indefinitely writing to the output stream (or3040* reading from the file). The behavior for the case that the output stream3041* is <i>asynchronously closed</i> or the thread interrupted during the copy3042* is highly output stream and file system provider specific and therefore3043* not specified.3044*3045* <p> Note that if the given output stream is {@link java.io.Flushable}3046* then its {@link java.io.Flushable#flush flush} method may need to invoked3047* after this method completes so as to flush any buffered output.3048*3049* @param source3050* the path to the file3051* @param out3052* the output stream to write to3053*3054* @return the number of bytes read or written3055*3056* @throws IOException3057* if an I/O error occurs when reading or writing3058* @throws SecurityException3059* In the case of the default provider, and a security manager is3060* installed, the {@link SecurityManager#checkRead(String) checkRead}3061* method is invoked to check read access to the file.3062*/3063public static long copy(Path source, OutputStream out) throws IOException {3064// ensure not null before opening file3065Objects.requireNonNull(out);30663067try (InputStream in = newInputStream(source)) {3068return copy(in, out);3069}3070}30713072/**3073* The maximum size of array to allocate.3074* Some VMs reserve some header words in an array.3075* Attempts to allocate larger arrays may result in3076* OutOfMemoryError: Requested array size exceeds VM limit3077*/3078private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;30793080/**3081* Reads all the bytes from an input stream. Uses {@code initialSize} as a hint3082* about how many bytes the stream will have.3083*3084* @param source3085* the input stream to read from3086* @param initialSize3087* the initial size of the byte array to allocate3088*3089* @return a byte array containing the bytes read from the file3090*3091* @throws IOException3092* if an I/O error occurs reading from the stream3093* @throws OutOfMemoryError3094* if an array of the required size cannot be allocated3095*/3096private static byte[] read(InputStream source, int initialSize) throws IOException {3097int capacity = initialSize;3098byte[] buf = new byte[capacity];3099int nread = 0;3100int n;3101for (;;) {3102// read to EOF which may read more or less than initialSize (eg: file3103// is truncated while we are reading)3104while ((n = source.read(buf, nread, capacity - nread)) > 0)3105nread += n;31063107// if last call to source.read() returned -1, we are done3108// otherwise, try to read one more byte; if that failed we're done too3109if (n < 0 || (n = source.read()) < 0)3110break;31113112// one more byte was read; need to allocate a larger buffer3113if (capacity <= MAX_BUFFER_SIZE - capacity) {3114capacity = Math.max(capacity << 1, BUFFER_SIZE);3115} else {3116if (capacity == MAX_BUFFER_SIZE)3117throw new OutOfMemoryError("Required array size too large");3118capacity = MAX_BUFFER_SIZE;3119}3120buf = Arrays.copyOf(buf, capacity);3121buf[nread++] = (byte)n;3122}3123return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);3124}31253126/**3127* Reads all the bytes from a file. The method ensures that the file is3128* closed when all bytes have been read or an I/O error, or other runtime3129* exception, is thrown.3130*3131* <p> Note that this method is intended for simple cases where it is3132* convenient to read all bytes into a byte array. It is not intended for3133* reading in large files.3134*3135* @param path3136* the path to the file3137*3138* @return a byte array containing the bytes read from the file3139*3140* @throws IOException3141* if an I/O error occurs reading from the stream3142* @throws OutOfMemoryError3143* if an array of the required size cannot be allocated, for3144* example the file is larger that {@code 2GB}3145* @throws SecurityException3146* In the case of the default provider, and a security manager is3147* installed, the {@link SecurityManager#checkRead(String) checkRead}3148* method is invoked to check read access to the file.3149*/3150public static byte[] readAllBytes(Path path) throws IOException {3151try (SeekableByteChannel sbc = Files.newByteChannel(path);3152InputStream in = Channels.newInputStream(sbc)) {3153long size = sbc.size();3154if (size > (long)MAX_BUFFER_SIZE)3155throw new OutOfMemoryError("Required array size too large");31563157return read(in, (int)size);3158}3159}31603161/**3162* Read all lines from a file. This method ensures that the file is3163* closed when all bytes have been read or an I/O error, or other runtime3164* exception, is thrown. Bytes from the file are decoded into characters3165* using the specified charset.3166*3167* <p> This method recognizes the following as line terminators:3168* <ul>3169* <li> <code>\u000D</code> followed by <code>\u000A</code>,3170* CARRIAGE RETURN followed by LINE FEED </li>3171* <li> <code>\u000A</code>, LINE FEED </li>3172* <li> <code>\u000D</code>, CARRIAGE RETURN </li>3173* </ul>3174* <p> Additional Unicode line terminators may be recognized in future3175* releases.3176*3177* <p> Note that this method is intended for simple cases where it is3178* convenient to read all lines in a single operation. It is not intended3179* for reading in large files.3180*3181* @param path3182* the path to the file3183* @param cs3184* the charset to use for decoding3185*3186* @return the lines from the file as a {@code List}; whether the {@code3187* List} is modifiable or not is implementation dependent and3188* therefore not specified3189*3190* @throws IOException3191* if an I/O error occurs reading from the file or a malformed or3192* unmappable byte sequence is read3193* @throws SecurityException3194* In the case of the default provider, and a security manager is3195* installed, the {@link SecurityManager#checkRead(String) checkRead}3196* method is invoked to check read access to the file.3197*3198* @see #newBufferedReader3199*/3200public static List<String> readAllLines(Path path, Charset cs) throws IOException {3201try (BufferedReader reader = newBufferedReader(path, cs)) {3202List<String> result = new ArrayList<>();3203for (;;) {3204String line = reader.readLine();3205if (line == null)3206break;3207result.add(line);3208}3209return result;3210}3211}32123213/**3214* Read all lines from a file. Bytes from the file are decoded into characters3215* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3216*3217* <p> This method works as if invoking it were equivalent to evaluating the3218* expression:3219* <pre>{@code3220* Files.readAllLines(path, StandardCharsets.UTF_8)3221* }</pre>3222*3223* @param path3224* the path to the file3225*3226* @return the lines from the file as a {@code List}; whether the {@code3227* List} is modifiable or not is implementation dependent and3228* therefore not specified3229*3230* @throws IOException3231* if an I/O error occurs reading from the file or a malformed or3232* unmappable byte sequence is read3233* @throws SecurityException3234* In the case of the default provider, and a security manager is3235* installed, the {@link SecurityManager#checkRead(String) checkRead}3236* method is invoked to check read access to the file.3237*3238* @since 1.83239*/3240public static List<String> readAllLines(Path path) throws IOException {3241return readAllLines(path, StandardCharsets.UTF_8);3242}32433244/**3245* Writes bytes to a file. The {@code options} parameter specifies how the3246* the file is created or opened. If no options are present then this method3247* works as if the {@link StandardOpenOption#CREATE CREATE}, {@link3248* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3249* StandardOpenOption#WRITE WRITE} options are present. In other words, it3250* opens the file for writing, creating the file if it doesn't exist, or3251* initially truncating an existing {@link #isRegularFile regular-file} to3252* a size of {@code 0}. All bytes in the byte array are written to the file.3253* The method ensures that the file is closed when all bytes have been3254* written (or an I/O error or other runtime exception is thrown). If an I/O3255* error occurs then it may do so after the file has created or truncated,3256* or after some bytes have been written to the file.3257*3258* <p> <b>Usage example</b>: By default the method creates a new file or3259* overwrites an existing file. Suppose you instead want to append bytes3260* to an existing file:3261* <pre>3262* Path path = ...3263* byte[] bytes = ...3264* Files.write(path, bytes, StandardOpenOption.APPEND);3265* </pre>3266*3267* @param path3268* the path to the file3269* @param bytes3270* the byte array with the bytes to write3271* @param options3272* options specifying how the file is opened3273*3274* @return the path3275*3276* @throws IOException3277* if an I/O error occurs writing to or creating the file3278* @throws UnsupportedOperationException3279* if an unsupported option is specified3280* @throws SecurityException3281* In the case of the default provider, and a security manager is3282* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3283* method is invoked to check write access to the file.3284*/3285public static Path write(Path path, byte[] bytes, OpenOption... options)3286throws IOException3287{3288// ensure bytes is not null before opening file3289Objects.requireNonNull(bytes);32903291try (OutputStream out = Files.newOutputStream(path, options)) {3292int len = bytes.length;3293int rem = len;3294while (rem > 0) {3295int n = Math.min(rem, BUFFER_SIZE);3296out.write(bytes, (len-rem), n);3297rem -= n;3298}3299}3300return path;3301}33023303/**3304* Write lines of text to a file. Each line is a char sequence and is3305* written to the file in sequence with each line terminated by the3306* platform's line separator, as defined by the system property {@code3307* line.separator}. Characters are encoded into bytes using the specified3308* charset.3309*3310* <p> The {@code options} parameter specifies how the the file is created3311* or opened. If no options are present then this method works as if the3312* {@link StandardOpenOption#CREATE CREATE}, {@link3313* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3314* StandardOpenOption#WRITE WRITE} options are present. In other words, it3315* opens the file for writing, creating the file if it doesn't exist, or3316* initially truncating an existing {@link #isRegularFile regular-file} to3317* a size of {@code 0}. The method ensures that the file is closed when all3318* lines have been written (or an I/O error or other runtime exception is3319* thrown). If an I/O error occurs then it may do so after the file has3320* created or truncated, or after some bytes have been written to the file.3321*3322* @param path3323* the path to the file3324* @param lines3325* an object to iterate over the char sequences3326* @param cs3327* the charset to use for encoding3328* @param options3329* options specifying how the file is opened3330*3331* @return the path3332*3333* @throws IOException3334* if an I/O error occurs writing to or creating the file, or the3335* text cannot be encoded using the specified charset3336* @throws UnsupportedOperationException3337* if an unsupported option is specified3338* @throws SecurityException3339* In the case of the default provider, and a security manager is3340* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3341* method is invoked to check write access to the file.3342*/3343public static Path write(Path path, Iterable<? extends CharSequence> lines,3344Charset cs, OpenOption... options)3345throws IOException3346{3347// ensure lines is not null before opening file3348Objects.requireNonNull(lines);3349CharsetEncoder encoder = cs.newEncoder();3350try (OutputStream out = newOutputStream(path, options);3351BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {3352for (CharSequence line: lines) {3353writer.append(line);3354writer.newLine();3355}3356}3357return path;3358}33593360/**3361* Write lines of text to a file. Characters are encoded into bytes using3362* the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3363*3364* <p> This method works as if invoking it were equivalent to evaluating the3365* expression:3366* <pre>{@code3367* Files.write(path, lines, StandardCharsets.UTF_8, options);3368* }</pre>3369*3370* @param path3371* the path to the file3372* @param lines3373* an object to iterate over the char sequences3374* @param options3375* options specifying how the file is opened3376*3377* @return the path3378*3379* @throws IOException3380* if an I/O error occurs writing to or creating the file, or the3381* text cannot be encoded as {@code UTF-8}3382* @throws UnsupportedOperationException3383* if an unsupported option is specified3384* @throws SecurityException3385* In the case of the default provider, and a security manager is3386* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3387* method is invoked to check write access to the file.3388*3389* @since 1.83390*/3391public static Path write(Path path,3392Iterable<? extends CharSequence> lines,3393OpenOption... options)3394throws IOException3395{3396return write(path, lines, StandardCharsets.UTF_8, options);3397}33983399// -- Stream APIs --34003401/**3402* Return a lazily populated {@code Stream}, the elements of3403* which are the entries in the directory. The listing is not recursive.3404*3405* <p> The elements of the stream are {@link Path} objects that are3406* obtained as if by {@link Path#resolve(Path) resolving} the name of the3407* directory entry against {@code dir}. Some file systems maintain special3408* links to the directory itself and the directory's parent directory.3409* Entries representing these links are not included.3410*3411* <p> The stream is <i>weakly consistent</i>. It is thread safe but does3412* not freeze the directory while iterating, so it may (or may not)3413* reflect updates to the directory that occur after returning from this3414* method.3415*3416* <p> The returned stream encapsulates a {@link DirectoryStream}.3417* If timely disposal of file system resources is required, the3418* {@code try}-with-resources construct should be used to ensure that the3419* stream's {@link Stream#close close} method is invoked after the stream3420* operations are completed.3421*3422* <p> Operating on a closed stream behaves as if the end of stream3423* has been reached. Due to read-ahead, one or more elements may be3424* returned after the stream has been closed.3425*3426* <p> If an {@link IOException} is thrown when accessing the directory3427* after this method has returned, it is wrapped in an {@link3428* UncheckedIOException} which will be thrown from the method that caused3429* the access to take place.3430*3431* @param dir The path to the directory3432*3433* @return The {@code Stream} describing the content of the3434* directory3435*3436* @throws NotDirectoryException3437* if the file could not otherwise be opened because it is not3438* a directory <i>(optional specific exception)</i>3439* @throws IOException3440* if an I/O error occurs when opening the directory3441* @throws SecurityException3442* In the case of the default provider, and a security manager is3443* installed, the {@link SecurityManager#checkRead(String) checkRead}3444* method is invoked to check read access to the directory.3445*3446* @see #newDirectoryStream(Path)3447* @since 1.83448*/3449public static Stream<Path> list(Path dir) throws IOException {3450DirectoryStream<Path> ds = Files.newDirectoryStream(dir);3451try {3452final Iterator<Path> delegate = ds.iterator();34533454// Re-wrap DirectoryIteratorException to UncheckedIOException3455Iterator<Path> it = new Iterator<Path>() {3456@Override3457public boolean hasNext() {3458try {3459return delegate.hasNext();3460} catch (DirectoryIteratorException e) {3461throw new UncheckedIOException(e.getCause());3462}3463}3464@Override3465public Path next() {3466try {3467return delegate.next();3468} catch (DirectoryIteratorException e) {3469throw new UncheckedIOException(e.getCause());3470}3471}3472};34733474return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false)3475.onClose(asUncheckedRunnable(ds));3476} catch (Error|RuntimeException e) {3477try {3478ds.close();3479} catch (IOException ex) {3480try {3481e.addSuppressed(ex);3482} catch (Throwable ignore) {}3483}3484throw e;3485}3486}34873488/**3489* Return a {@code Stream} that is lazily populated with {@code3490* Path} by walking the file tree rooted at a given starting file. The3491* file tree is traversed <em>depth-first</em>, the elements in the stream3492* are {@link Path} objects that are obtained as if by {@link3493* Path#resolve(Path) resolving} the relative path against {@code start}.3494*3495* <p> The {@code stream} walks the file tree as elements are consumed.3496* The {@code Stream} returned is guaranteed to have at least one3497* element, the starting file itself. For each file visited, the stream3498* attempts to read its {@link BasicFileAttributes}. If the file is a3499* directory and can be opened successfully, entries in the directory, and3500* their <em>descendants</em> will follow the directory in the stream as3501* they are encountered. When all entries have been visited, then the3502* directory is closed. The file tree walk then continues at the next3503* <em>sibling</em> of the directory.3504*3505* <p> The stream is <i>weakly consistent</i>. It does not freeze the3506* file tree while iterating, so it may (or may not) reflect updates to3507* the file tree that occur after returned from this method.3508*3509* <p> By default, symbolic links are not automatically followed by this3510* method. If the {@code options} parameter contains the {@link3511* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are3512* followed. When following links, and the attributes of the target cannot3513* be read, then this method attempts to get the {@code BasicFileAttributes}3514* of the link.3515*3516* <p> If the {@code options} parameter contains the {@link3517* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then the stream keeps3518* track of directories visited so that cycles can be detected. A cycle3519* arises when there is an entry in a directory that is an ancestor of the3520* directory. Cycle detection is done by recording the {@link3521* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,3522* or if file keys are not available, by invoking the {@link #isSameFile3523* isSameFile} method to test if a directory is the same file as an3524* ancestor. When a cycle is detected it is treated as an I/O error with3525* an instance of {@link FileSystemLoopException}.3526*3527* <p> The {@code maxDepth} parameter is the maximum number of levels of3528* directories to visit. A value of {@code 0} means that only the starting3529* file is visited, unless denied by the security manager. A value of3530* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all3531* levels should be visited.3532*3533* <p> When a security manager is installed and it denies access to a file3534* (or directory), then it is ignored and not included in the stream.3535*3536* <p> The returned stream encapsulates one or more {@link DirectoryStream}s.3537* If timely disposal of file system resources is required, the3538* {@code try}-with-resources construct should be used to ensure that the3539* stream's {@link Stream#close close} method is invoked after the stream3540* operations are completed. Operating on a closed stream will result in an3541* {@link java.lang.IllegalStateException}.3542*3543* <p> If an {@link IOException} is thrown when accessing the directory3544* after this method has returned, it is wrapped in an {@link3545* UncheckedIOException} which will be thrown from the method that caused3546* the access to take place.3547*3548* @param start3549* the starting file3550* @param maxDepth3551* the maximum number of directory levels to visit3552* @param options3553* options to configure the traversal3554*3555* @return the {@link Stream} of {@link Path}3556*3557* @throws IllegalArgumentException3558* if the {@code maxDepth} parameter is negative3559* @throws SecurityException3560* If the security manager denies access to the starting file.3561* In the case of the default provider, the {@link3562* SecurityManager#checkRead(String) checkRead} method is invoked3563* to check read access to the directory.3564* @throws IOException3565* if an I/O error is thrown when accessing the starting file.3566* @since 1.83567*/3568public static Stream<Path> walk(Path start,3569int maxDepth,3570FileVisitOption... options)3571throws IOException3572{3573FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);3574try {3575return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), false)3576.onClose(iterator::close)3577.map(entry -> entry.file());3578} catch (Error|RuntimeException e) {3579iterator.close();3580throw e;3581}3582}35833584/**3585* Return a {@code Stream} that is lazily populated with {@code3586* Path} by walking the file tree rooted at a given starting file. The3587* file tree is traversed <em>depth-first</em>, the elements in the stream3588* are {@link Path} objects that are obtained as if by {@link3589* Path#resolve(Path) resolving} the relative path against {@code start}.3590*3591* <p> This method works as if invoking it were equivalent to evaluating the3592* expression:3593* <blockquote><pre>3594* walk(start, Integer.MAX_VALUE, options)3595* </pre></blockquote>3596* In other words, it visits all levels of the file tree.3597*3598* <p> The returned stream encapsulates one or more {@link DirectoryStream}s.3599* If timely disposal of file system resources is required, the3600* {@code try}-with-resources construct should be used to ensure that the3601* stream's {@link Stream#close close} method is invoked after the stream3602* operations are completed. Operating on a closed stream will result in an3603* {@link java.lang.IllegalStateException}.3604*3605* @param start3606* the starting file3607* @param options3608* options to configure the traversal3609*3610* @return the {@link Stream} of {@link Path}3611*3612* @throws SecurityException3613* If the security manager denies access to the starting file.3614* In the case of the default provider, the {@link3615* SecurityManager#checkRead(String) checkRead} method is invoked3616* to check read access to the directory.3617* @throws IOException3618* if an I/O error is thrown when accessing the starting file.3619*3620* @see #walk(Path, int, FileVisitOption...)3621* @since 1.83622*/3623public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException {3624return walk(start, Integer.MAX_VALUE, options);3625}36263627/**3628* Return a {@code Stream} that is lazily populated with {@code3629* Path} by searching for files in a file tree rooted at a given starting3630* file.3631*3632* <p> This method walks the file tree in exactly the manner specified by3633* the {@link #walk walk} method. For each file encountered, the given3634* {@link BiPredicate} is invoked with its {@link Path} and {@link3635* BasicFileAttributes}. The {@code Path} object is obtained as if by3636* {@link Path#resolve(Path) resolving} the relative path against {@code3637* start} and is only included in the returned {@link Stream} if3638* the {@code BiPredicate} returns true. Compare to calling {@link3639* java.util.stream.Stream#filter filter} on the {@code Stream}3640* returned by {@code walk} method, this method may be more efficient by3641* avoiding redundant retrieval of the {@code BasicFileAttributes}.3642*3643* <p> The returned stream encapsulates one or more {@link DirectoryStream}s.3644* If timely disposal of file system resources is required, the3645* {@code try}-with-resources construct should be used to ensure that the3646* stream's {@link Stream#close close} method is invoked after the stream3647* operations are completed. Operating on a closed stream will result in an3648* {@link java.lang.IllegalStateException}.3649*3650* <p> If an {@link IOException} is thrown when accessing the directory3651* after returned from this method, it is wrapped in an {@link3652* UncheckedIOException} which will be thrown from the method that caused3653* the access to take place.3654*3655* @param start3656* the starting file3657* @param maxDepth3658* the maximum number of directory levels to search3659* @param matcher3660* the function used to decide whether a file should be included3661* in the returned stream3662* @param options3663* options to configure the traversal3664*3665* @return the {@link Stream} of {@link Path}3666*3667* @throws IllegalArgumentException3668* if the {@code maxDepth} parameter is negative3669* @throws SecurityException3670* If the security manager denies access to the starting file.3671* In the case of the default provider, the {@link3672* SecurityManager#checkRead(String) checkRead} method is invoked3673* to check read access to the directory.3674* @throws IOException3675* if an I/O error is thrown when accessing the starting file.3676*3677* @see #walk(Path, int, FileVisitOption...)3678* @since 1.83679*/3680public static Stream<Path> find(Path start,3681int maxDepth,3682BiPredicate<Path, BasicFileAttributes> matcher,3683FileVisitOption... options)3684throws IOException3685{3686FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);3687try {3688return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), false)3689.onClose(iterator::close)3690.filter(entry -> matcher.test(entry.file(), entry.attributes()))3691.map(entry -> entry.file());3692} catch (Error|RuntimeException e) {3693iterator.close();3694throw e;3695}3696}36973698/**3699* Read all lines from a file as a {@code Stream}. Unlike {@link3700* #readAllLines(Path, Charset) readAllLines}, this method does not read3701* all lines into a {@code List}, but instead populates lazily as the stream3702* is consumed.3703*3704* <p> Bytes from the file are decoded into characters using the specified3705* charset and the same line terminators as specified by {@code3706* readAllLines} are supported.3707*3708* <p> After this method returns, then any subsequent I/O exception that3709* occurs while reading from the file or when a malformed or unmappable byte3710* sequence is read, is wrapped in an {@link UncheckedIOException} that will3711* be thrown from the3712* {@link java.util.stream.Stream} method that caused the read to take3713* place. In case an {@code IOException} is thrown when closing the file,3714* it is also wrapped as an {@code UncheckedIOException}.3715*3716* <p> The returned stream encapsulates a {@link Reader}. If timely3717* disposal of file system resources is required, the try-with-resources3718* construct should be used to ensure that the stream's3719* {@link Stream#close close} method is invoked after the stream operations3720* are completed.3721*3722*3723* @param path3724* the path to the file3725* @param cs3726* the charset to use for decoding3727*3728* @return the lines from the file as a {@code Stream}3729*3730* @throws IOException3731* if an I/O error occurs opening the file3732* @throws SecurityException3733* In the case of the default provider, and a security manager is3734* installed, the {@link SecurityManager#checkRead(String) checkRead}3735* method is invoked to check read access to the file.3736*3737* @see #readAllLines(Path, Charset)3738* @see #newBufferedReader(Path, Charset)3739* @see java.io.BufferedReader#lines()3740* @since 1.83741*/3742public static Stream<String> lines(Path path, Charset cs) throws IOException {3743BufferedReader br = Files.newBufferedReader(path, cs);3744try {3745return br.lines().onClose(asUncheckedRunnable(br));3746} catch (Error|RuntimeException e) {3747try {3748br.close();3749} catch (IOException ex) {3750try {3751e.addSuppressed(ex);3752} catch (Throwable ignore) {}3753}3754throw e;3755}3756}37573758/**3759* Read all lines from a file as a {@code Stream}. Bytes from the file are3760* decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8}3761* {@link Charset charset}.3762*3763* <p> This method works as if invoking it were equivalent to evaluating the3764* expression:3765* <pre>{@code3766* Files.lines(path, StandardCharsets.UTF_8)3767* }</pre>3768*3769* @param path3770* the path to the file3771*3772* @return the lines from the file as a {@code Stream}3773*3774* @throws IOException3775* if an I/O error occurs opening the file3776* @throws SecurityException3777* In the case of the default provider, and a security manager is3778* installed, the {@link SecurityManager#checkRead(String) checkRead}3779* method is invoked to check read access to the file.3780*3781* @since 1.83782*/3783public static Stream<String> lines(Path path) throws IOException {3784return lines(path, StandardCharsets.UTF_8);3785}3786}378737883789