Path: blob/master/src/java.base/share/classes/java/nio/file/Files.java
41159 views
/*1* Copyright (c) 2007, 2021, 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;7879import jdk.internal.util.ArraysSupport;80import sun.nio.ch.FileChannelImpl;81import sun.nio.cs.UTF_8;82import sun.nio.fs.AbstractFileSystemProvider;8384/**85* This class consists exclusively of static methods that operate on files,86* directories, or other types of files.87*88* <p> In most cases, the methods defined here will delegate to the associated89* file system provider to perform the file operations.90*91* @since 1.792*/9394public final class Files {95// buffer size used for reading and writing96private static final int BUFFER_SIZE = 8192;9798private Files() { }99100/**101* Returns the {@code FileSystemProvider} to delegate to.102*/103private static FileSystemProvider provider(Path path) {104return path.getFileSystem().provider();105}106107/**108* Convert a Closeable to a Runnable by converting checked IOException109* to UncheckedIOException110*/111private static Runnable asUncheckedRunnable(Closeable c) {112return () -> {113try {114c.close();115} catch (IOException e) {116throw new UncheckedIOException(e);117}118};119}120121// -- File contents --122123/**124* Opens a file, returning an input stream to read from the file. The stream125* will not be buffered, and is not required to support the {@link126* InputStream#mark mark} or {@link InputStream#reset reset} methods. The127* stream will be safe for access by multiple concurrent threads. Reading128* commences at the beginning of the file. Whether the returned stream is129* <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly130* file system provider specific and therefore not specified.131*132* <p> The {@code options} parameter determines how the file is opened.133* If no options are present then it is equivalent to opening the file with134* the {@link StandardOpenOption#READ READ} option. In addition to the {@code135* READ} option, an implementation may also support additional implementation136* specific options.137*138* @param path139* the path to the file to open140* @param options141* options specifying how the file is opened142*143* @return a new input stream144*145* @throws IllegalArgumentException146* if an invalid combination of options is specified147* @throws UnsupportedOperationException148* if an unsupported option is specified149* @throws IOException150* if an I/O error occurs151* @throws SecurityException152* In the case of the default provider, and a security manager is153* installed, the {@link SecurityManager#checkRead(String) checkRead}154* method is invoked to check read access to the file.155*/156public static InputStream newInputStream(Path path, OpenOption... options)157throws IOException158{159return provider(path).newInputStream(path, options);160}161162/**163* Opens or creates a file, returning an output stream that may be used to164* write bytes to the file. The resulting stream will not be buffered. The165* stream will be safe for access by multiple concurrent threads. Whether166* the returned stream is <i>asynchronously closeable</i> and/or167* <i>interruptible</i> is highly file system provider specific and168* therefore not specified.169*170* <p> This method opens or creates a file in exactly the manner specified171* by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}172* method with the exception that the {@link StandardOpenOption#READ READ}173* option may not be present in the array of options. If no options are174* present then this method works as if the {@link StandardOpenOption#CREATE175* CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING},176* and {@link StandardOpenOption#WRITE WRITE} options are present. In other177* words, it opens the file for writing, creating the file if it doesn't178* exist, or initially truncating an existing {@link #isRegularFile179* regular-file} to a size of {@code 0} if it exists.180*181* <p> <b>Usage Examples:</b>182* <pre>183* Path path = ...184*185* // truncate and overwrite an existing file, or create the file if186* // it doesn't initially exist187* OutputStream out = Files.newOutputStream(path);188*189* // append to an existing file, fail if the file does not exist190* out = Files.newOutputStream(path, APPEND);191*192* // append to an existing file, create file if it doesn't initially exist193* out = Files.newOutputStream(path, CREATE, APPEND);194*195* // always create new file, failing if it already exists196* out = Files.newOutputStream(path, CREATE_NEW);197* </pre>198*199* @param path200* the path to the file to open or create201* @param options202* options specifying how the file is opened203*204* @return a new output stream205*206* @throws IllegalArgumentException207* if {@code options} contains an invalid combination of options208* @throws UnsupportedOperationException209* if an unsupported option is specified210* @throws FileAlreadyExistsException211* If a file of that name already exists and the {@link212* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified213* <i>(optional specific exception)</i>214* @throws IOException215* if an I/O error occurs216* @throws SecurityException217* In the case of the default provider, and a security manager is218* installed, the {@link SecurityManager#checkWrite(String) checkWrite}219* method is invoked to check write access to the file. The {@link220* SecurityManager#checkDelete(String) checkDelete} method is221* invoked to check delete access if the file is opened with the222* {@code DELETE_ON_CLOSE} option.223*/224public static OutputStream newOutputStream(Path path, OpenOption... options)225throws IOException226{227return provider(path).newOutputStream(path, options);228}229230/**231* Opens or creates a file, returning a seekable byte channel to access the232* file.233*234* <p> The {@code options} parameter determines how the file is opened.235* The {@link StandardOpenOption#READ READ} and {@link236* StandardOpenOption#WRITE WRITE} options determine if the file should be237* opened for reading and/or writing. If neither option (or the {@link238* StandardOpenOption#APPEND APPEND} option) is present then the file is239* opened for reading. By default reading or writing commence at the240* beginning of the file.241*242* <p> In the addition to {@code READ} and {@code WRITE}, the following243* options may be present:244*245* <table class="striped">246* <caption style="display:none">Options</caption>247* <thead>248* <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>249* </thead>250* <tbody>251* <tr>252* <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th>253* <td> If this option is present then the file is opened for writing and254* each invocation of the channel's {@code write} method first advances255* the position to the end of the file and then writes the requested256* data. Whether the advancement of the position and the writing of the257* data are done in a single atomic operation is system-dependent and258* therefore unspecified. This option may not be used in conjunction259* with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>260* </tr>261* <tr>262* <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th>263* <td> If this option is present then the existing file is truncated to264* a size of 0 bytes. This option is ignored when the file is opened only265* for reading. </td>266* </tr>267* <tr>268* <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th>269* <td> If this option is present then a new file is created, failing if270* the file already exists or is a symbolic link. When creating a file the271* check for the existence of the file and the creation of the file if it272* does not exist is atomic with respect to other file system operations.273* This option is ignored when the file is opened only for reading. </td>274* </tr>275* <tr>276* <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th>277* <td> If this option is present then an existing file is opened if it278* exists, otherwise a new file is created. This option is ignored if the279* {@code CREATE_NEW} option is also present or the file is opened only280* for reading. </td>281* </tr>282* <tr>283* <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th>284* <td> When this option is present then the implementation makes a285* <em>best effort</em> attempt to delete the file when closed by the286* {@link SeekableByteChannel#close close} method. If the {@code close}287* method is not invoked then a <em>best effort</em> attempt is made to288* delete the file when the Java virtual machine terminates. </td>289* </tr>290* <tr>291* <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th>292* <td> When creating a new file this option is a <em>hint</em> that the293* new file will be sparse. This option is ignored when not creating294* a new file. </td>295* </tr>296* <tr>297* <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th>298* <td> Requires that every update to the file's content or metadata be299* written synchronously to the underlying storage device. (see <a300* href="package-summary.html#integrity"> Synchronized I/O file301* integrity</a>). </td>302* </tr>303* <tr>304* <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th>305* <td> Requires that every update to the file's content be written306* synchronously to the underlying storage device. (see <a307* href="package-summary.html#integrity"> Synchronized I/O file308* integrity</a>). </td>309* </tr>310* </tbody>311* </table>312*313* <p> An implementation may also support additional implementation specific314* options.315*316* <p> The {@code attrs} parameter is optional {@link FileAttribute317* file-attributes} to set atomically when a new file is created.318*319* <p> In the case of the default provider, the returned seekable byte channel320* is a {@link java.nio.channels.FileChannel}.321*322* <p> <b>Usage Examples:</b>323* <pre>{@code324* Path path = ...325*326* // open file for reading327* ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ)));328*329* // open file for writing to the end of an existing file, creating330* // the file if it doesn't already exist331* WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND));332*333* // create file with initial permissions, opening it for both reading and writing334* FileAttribute<Set<PosixFilePermission>> perms = ...335* SeekableByteChannel sbc =336* Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms);337* }</pre>338*339* @param path340* the path to the file to open or create341* @param options342* options specifying how the file is opened343* @param attrs344* an optional list of file attributes to set atomically when345* creating the file346*347* @return a new seekable byte channel348*349* @throws IllegalArgumentException350* if the set contains an invalid combination of options351* @throws UnsupportedOperationException352* if an unsupported open option is specified or the array contains353* attributes that cannot be set atomically when creating the file354* @throws FileAlreadyExistsException355* If a file of that name already exists and the {@link356* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified357* and the file is being opened for writing <i>(optional specific358* exception)</i>359* @throws IOException360* if an I/O error occurs361* @throws SecurityException362* In the case of the default provider, and a security manager is363* installed, the {@link SecurityManager#checkRead(String) checkRead}364* method is invoked to check read access to the path if the file is365* opened for reading. The {@link SecurityManager#checkWrite(String)366* checkWrite} method is invoked to check write access to the path367* if the file is opened for writing. The {@link368* SecurityManager#checkDelete(String) checkDelete} method is369* invoked to check delete access if the file is opened with the370* {@code DELETE_ON_CLOSE} option.371*372* @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[])373*/374public static SeekableByteChannel newByteChannel(Path path,375Set<? extends OpenOption> options,376FileAttribute<?>... attrs)377throws IOException378{379return provider(path).newByteChannel(path, options, attrs);380}381382/**383* Opens or creates a file, returning a seekable byte channel to access the384* file.385*386* <p> This method opens or creates a file in exactly the manner specified387* by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel}388* method.389*390* @param path391* the path to the file to open or create392* @param options393* options specifying how the file is opened394*395* @return a new seekable byte channel396*397* @throws IllegalArgumentException398* if the set contains an invalid combination of options399* @throws UnsupportedOperationException400* if an unsupported open option is specified401* @throws FileAlreadyExistsException402* If a file of that name already exists and the {@link403* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified404* and the file is being opened for writing <i>(optional specific405* exception)</i>406* @throws IOException407* if an I/O error occurs408* @throws SecurityException409* In the case of the default provider, and a security manager is410* installed, the {@link SecurityManager#checkRead(String) checkRead}411* method is invoked to check read access to the path if the file is412* opened for reading. The {@link SecurityManager#checkWrite(String)413* checkWrite} method is invoked to check write access to the path414* if the file is opened for writing. The {@link415* SecurityManager#checkDelete(String) checkDelete} method is416* invoked to check delete access if the file is opened with the417* {@code DELETE_ON_CLOSE} option.418*419* @see java.nio.channels.FileChannel#open(Path,OpenOption[])420*/421public static SeekableByteChannel newByteChannel(Path path, OpenOption... options)422throws IOException423{424Set<OpenOption> set;425if (options.length == 0) {426set = Collections.emptySet();427} else {428set = new HashSet<>();429Collections.addAll(set, options);430}431return newByteChannel(path, set);432}433434// -- Directories --435436private static class AcceptAllFilter437implements DirectoryStream.Filter<Path>438{439private AcceptAllFilter() { }440441@Override442public boolean accept(Path entry) { return true; }443444static final AcceptAllFilter FILTER = new AcceptAllFilter();445}446447/**448* Opens a directory, returning a {@link DirectoryStream} to iterate over449* all entries in the directory. The elements returned by the directory450* stream's {@link DirectoryStream#iterator iterator} are of type {@code451* Path}, each one representing an entry in the directory. The {@code Path}452* objects are obtained as if by {@link Path#resolve(Path) resolving} the453* name of the directory entry against {@code dir}.454*455* <p> When not using the try-with-resources construct, then directory456* stream's {@code close} method should be invoked after iteration is457* completed so as to free any resources held for the open directory.458*459* <p> When an implementation supports operations on entries in the460* directory that execute in a race-free manner then the returned directory461* stream is a {@link SecureDirectoryStream}.462*463* @param dir464* the path to the directory465*466* @return a new and open {@code DirectoryStream} object467*468* @throws NotDirectoryException469* if the file could not otherwise be opened because it is not470* a directory <i>(optional specific exception)</i>471* @throws IOException472* if an I/O error occurs473* @throws SecurityException474* In the case of the default provider, and a security manager is475* installed, the {@link SecurityManager#checkRead(String) checkRead}476* method is invoked to check read access to the directory.477*/478public static DirectoryStream<Path> newDirectoryStream(Path dir)479throws IOException480{481return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER);482}483484/**485* Opens a directory, returning a {@link DirectoryStream} to iterate over486* the entries in the directory. The elements returned by the directory487* stream's {@link DirectoryStream#iterator iterator} are of type {@code488* Path}, each one representing an entry in the directory. The {@code Path}489* objects are obtained as if by {@link Path#resolve(Path) resolving} the490* name of the directory entry against {@code dir}. The entries returned by491* the iterator are filtered by matching the {@code String} representation492* of their file names against the given <em>globbing</em> pattern.493*494* <p> For example, suppose we want to iterate over the files ending with495* ".java" in a directory:496* <pre>497* Path dir = ...498* try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) {499* :500* }501* </pre>502*503* <p> The globbing pattern is specified by the {@link504* FileSystem#getPathMatcher getPathMatcher} method.505*506* <p> When not using the try-with-resources construct, then directory507* stream's {@code close} method should be invoked after iteration is508* completed so as to free any resources held for the open directory.509*510* <p> When an implementation supports operations on entries in the511* directory that execute in a race-free manner then the returned directory512* stream is a {@link SecureDirectoryStream}.513*514* @param dir515* the path to the directory516* @param glob517* the glob pattern518*519* @return a new and open {@code DirectoryStream} object520*521* @throws java.util.regex.PatternSyntaxException522* if the pattern is invalid523* @throws NotDirectoryException524* if the file could not otherwise be opened because it is not525* a directory <i>(optional specific exception)</i>526* @throws IOException527* if an I/O error occurs528* @throws SecurityException529* In the case of the default provider, and a security manager is530* installed, the {@link SecurityManager#checkRead(String) checkRead}531* method is invoked to check read access to the directory.532*/533public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob)534throws IOException535{536// avoid creating a matcher if all entries are required.537if (glob.equals("*"))538return newDirectoryStream(dir);539540// create a matcher and return a filter that uses it.541FileSystem fs = dir.getFileSystem();542final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);543DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<>() {544@Override545public boolean accept(Path entry) {546return matcher.matches(entry.getFileName());547}548};549return fs.provider().newDirectoryStream(dir, filter);550}551552/**553* Opens a directory, returning a {@link DirectoryStream} to iterate over554* the entries in the directory. The elements returned by the directory555* stream's {@link DirectoryStream#iterator iterator} are of type {@code556* Path}, each one representing an entry in the directory. The {@code Path}557* objects are obtained as if by {@link Path#resolve(Path) resolving} the558* name of the directory entry against {@code dir}. The entries returned by559* the iterator are filtered by the given {@link DirectoryStream.Filter560* filter}.561*562* <p> When not using the try-with-resources construct, then directory563* stream's {@code close} method should be invoked after iteration is564* completed so as to free any resources held for the open directory.565*566* <p> Where the filter terminates due to an uncaught error or runtime567* exception then it is propagated to the {@link Iterator#hasNext()568* hasNext} or {@link Iterator#next() next} method. Where an {@code569* IOException} is thrown, it results in the {@code hasNext} or {@code570* next} method throwing a {@link DirectoryIteratorException} with the571* {@code IOException} as the cause.572*573* <p> When an implementation supports operations on entries in the574* directory that execute in a race-free manner then the returned directory575* stream is a {@link SecureDirectoryStream}.576*577* <p> <b>Usage Example:</b>578* Suppose we want to iterate over the files in a directory that are579* larger than 8K.580* <pre>581* DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {582* public boolean accept(Path file) throws IOException {583* return (Files.size(file) > 8192L);584* }585* };586* Path dir = ...587* try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {588* :589* }590* </pre>591*592* @param dir593* the path to the directory594* @param filter595* the directory stream filter596*597* @return a new and open {@code DirectoryStream} object598*599* @throws NotDirectoryException600* if the file could not otherwise be opened because it is not601* a directory <i>(optional specific exception)</i>602* @throws IOException603* if an I/O error occurs604* @throws SecurityException605* In the case of the default provider, and a security manager is606* installed, the {@link SecurityManager#checkRead(String) checkRead}607* method is invoked to check read access to the directory.608*/609public static DirectoryStream<Path> newDirectoryStream(Path dir,610DirectoryStream.Filter<? super Path> filter)611throws IOException612{613return provider(dir).newDirectoryStream(dir, filter);614}615616// -- Creation and deletion --617618private static final Set<OpenOption> DEFAULT_CREATE_OPTIONS =619Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);620621/**622* Creates a new and empty file, failing if the file already exists. The623* check for the existence of the file and the creation of the new file if624* it does not exist are a single operation that is atomic with respect to625* all other filesystem activities that might affect the directory.626*627* <p> The {@code attrs} parameter is optional {@link FileAttribute628* file-attributes} to set atomically when creating the file. Each attribute629* is identified by its {@link FileAttribute#name name}. If more than one630* attribute of the same name is included in the array then all but the last631* occurrence is ignored.632*633* @param path634* the path to the file to create635* @param attrs636* an optional list of file attributes to set atomically when637* creating the file638*639* @return the file640*641* @throws UnsupportedOperationException642* if the array contains an attribute that cannot be set atomically643* when creating the file644* @throws FileAlreadyExistsException645* If a file of that name already exists646* <i>(optional specific exception)</i>647* @throws IOException648* if an I/O error occurs or the parent directory does not exist649* @throws SecurityException650* In the case of the default provider, and a security manager is651* installed, the {@link SecurityManager#checkWrite(String) checkWrite}652* method is invoked to check write access to the new file.653*/654public static Path createFile(Path path, FileAttribute<?>... attrs)655throws IOException656{657newByteChannel(path, DEFAULT_CREATE_OPTIONS, attrs).close();658return path;659}660661/**662* Creates a new directory. The check for the existence of the file and the663* creation of the directory if it does not exist are a single operation664* that is atomic with respect to all other filesystem activities that might665* affect the directory. The {@link #createDirectories createDirectories}666* method should be used where it is required to create all nonexistent667* parent directories first.668*669* <p> The {@code attrs} parameter is optional {@link FileAttribute670* file-attributes} to set atomically when creating the directory. Each671* attribute is identified by its {@link FileAttribute#name name}. If more672* than one attribute of the same name is included in the array then all but673* the last occurrence is ignored.674*675* @param dir676* the directory to create677* @param attrs678* an optional list of file attributes to set atomically when679* creating the directory680*681* @return the directory682*683* @throws UnsupportedOperationException684* if the array contains an attribute that cannot be set atomically685* when creating the directory686* @throws FileAlreadyExistsException687* if a directory could not otherwise be created because a file of688* that name already exists <i>(optional specific exception)</i>689* @throws IOException690* if an I/O error occurs or the parent directory does not exist691* @throws SecurityException692* In the case of the default provider, and a security manager is693* installed, the {@link SecurityManager#checkWrite(String) checkWrite}694* method is invoked to check write access to the new directory.695*/696public static Path createDirectory(Path dir, FileAttribute<?>... attrs)697throws IOException698{699provider(dir).createDirectory(dir, attrs);700return dir;701}702703/**704* Creates a directory by creating all nonexistent parent directories first.705* Unlike the {@link #createDirectory createDirectory} method, an exception706* is not thrown if the directory could not be created because it already707* exists.708*709* <p> The {@code attrs} parameter is optional {@link FileAttribute710* file-attributes} to set atomically when creating the nonexistent711* directories. Each file attribute is identified by its {@link712* FileAttribute#name name}. If more than one attribute of the same name is713* included in the array then all but the last occurrence is ignored.714*715* <p> If this method fails, then it may do so after creating some, but not716* all, of the parent directories.717*718* @param dir719* the directory to create720*721* @param attrs722* an optional list of file attributes to set atomically when723* creating the directory724*725* @return the directory726*727* @throws UnsupportedOperationException728* if the array contains an attribute that cannot be set atomically729* when creating the directory730* @throws FileAlreadyExistsException731* if {@code dir} exists but is not a directory <i>(optional specific732* exception)</i>733* @throws IOException734* if an I/O error occurs735* @throws SecurityException736* in the case of the default provider, and a security manager is737* installed, the {@link SecurityManager#checkWrite(String) checkWrite}738* method is invoked prior to attempting to create a directory and739* its {@link SecurityManager#checkRead(String) checkRead} is740* invoked for each parent directory that is checked. If {@code741* dir} is not an absolute path then its {@link Path#toAbsolutePath742* toAbsolutePath} may need to be invoked to get its absolute path.743* This may invoke the security manager's {@link744* SecurityManager#checkPropertyAccess(String) checkPropertyAccess}745* method to check access to the system property {@code user.dir}746*/747public static Path createDirectories(Path dir, FileAttribute<?>... attrs)748throws IOException749{750// attempt to create the directory751try {752createAndCheckIsDirectory(dir, attrs);753return dir;754} catch (FileAlreadyExistsException x) {755// file exists and is not a directory756throw x;757} catch (IOException x) {758// parent may not exist or other reason759}760SecurityException se = null;761try {762dir = dir.toAbsolutePath();763} catch (SecurityException x) {764// don't have permission to get absolute path765se = x;766}767// find a descendant that exists768Path parent = dir.getParent();769while (parent != null) {770try {771provider(parent).checkAccess(parent);772break;773} catch (NoSuchFileException x) {774// does not exist775}776parent = parent.getParent();777}778if (parent == null) {779// unable to find existing parent780if (se == null) {781throw new FileSystemException(dir.toString(), null,782"Unable to determine if root directory exists");783} else {784throw se;785}786}787788// create directories789Path child = parent;790for (Path name: parent.relativize(dir)) {791child = child.resolve(name);792createAndCheckIsDirectory(child, attrs);793}794return dir;795}796797/**798* Used by createDirectories to attempt to create a directory. A no-op799* if the directory already exists.800*/801private static void createAndCheckIsDirectory(Path dir,802FileAttribute<?>... attrs)803throws IOException804{805try {806createDirectory(dir, attrs);807} catch (FileAlreadyExistsException x) {808if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS))809throw x;810}811}812813/**814* Creates a new empty file in the specified directory, using the given815* prefix and suffix strings to generate its name. The resulting816* {@code Path} is associated with the same {@code FileSystem} as the given817* directory.818*819* <p> The details as to how the name of the file is constructed is820* implementation dependent and therefore not specified. Where possible821* the {@code prefix} and {@code suffix} are used to construct candidate822* names in the same manner as the {@link823* java.io.File#createTempFile(String,String,File)} method.824*825* <p> As with the {@code File.createTempFile} methods, this method is only826* part of a temporary-file facility. Where used as a <em>work files</em>,827* the resulting file may be opened using the {@link828* StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the829* file is deleted when the appropriate {@code close} method is invoked.830* Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the831* {@link java.io.File#deleteOnExit} mechanism may be used to delete the832* file automatically.833*834* <p> The {@code attrs} parameter is optional {@link FileAttribute835* file-attributes} to set atomically when creating the file. Each attribute836* is identified by its {@link FileAttribute#name name}. If more than one837* attribute of the same name is included in the array then all but the last838* occurrence is ignored. When no file attributes are specified, then the839* resulting file may have more restrictive access permissions to files840* created by the {@link java.io.File#createTempFile(String,String,File)}841* method.842*843* @param dir844* the path to directory in which to create the file845* @param prefix846* the prefix string to be used in generating the file's name;847* may be {@code null}848* @param suffix849* the suffix string to be used in generating the file's name;850* may be {@code null}, in which case "{@code .tmp}" is used851* @param attrs852* an optional list of file attributes to set atomically when853* creating the file854*855* @return the path to the newly created file that did not exist before856* this method was invoked857*858* @throws IllegalArgumentException859* if the prefix or suffix parameters cannot be used to generate860* a candidate file name861* @throws UnsupportedOperationException862* if the array contains an attribute that cannot be set atomically863* when creating the directory864* @throws IOException865* if an I/O error occurs or {@code dir} does not exist866* @throws SecurityException867* In the case of the default provider, and a security manager is868* installed, the {@link SecurityManager#checkWrite(String) checkWrite}869* method is invoked to check write access to the file.870*/871public static Path createTempFile(Path dir,872String prefix,873String suffix,874FileAttribute<?>... attrs)875throws IOException876{877return TempFileHelper.createTempFile(Objects.requireNonNull(dir),878prefix, suffix, attrs);879}880881/**882* Creates an empty file in the default temporary-file directory, using883* the given prefix and suffix to generate its name. The resulting {@code884* Path} is associated with the default {@code FileSystem}.885*886* <p> This method works in exactly the manner specified by the887* {@link #createTempFile(Path,String,String,FileAttribute[])} method for888* the case that the {@code dir} parameter is the temporary-file directory.889*890* @param prefix891* the prefix string to be used in generating the file's name;892* may be {@code null}893* @param suffix894* the suffix string to be used in generating the file's name;895* may be {@code null}, in which case "{@code .tmp}" is used896* @param attrs897* an optional list of file attributes to set atomically when898* creating the file899*900* @return the path to the newly created file that did not exist before901* this method was invoked902*903* @throws IllegalArgumentException904* if the prefix or suffix parameters cannot be used to generate905* a candidate file name906* @throws UnsupportedOperationException907* if the array contains an attribute that cannot be set atomically908* when creating the directory909* @throws IOException910* if an I/O error occurs or the temporary-file directory does not911* exist912* @throws SecurityException913* In the case of the default provider, and a security manager is914* installed, the {@link SecurityManager#checkWrite(String) checkWrite}915* method is invoked to check write access to the file.916*/917public static Path createTempFile(String prefix,918String suffix,919FileAttribute<?>... attrs)920throws IOException921{922return TempFileHelper.createTempFile(null, prefix, suffix, attrs);923}924925/**926* Creates a new directory in the specified directory, using the given927* prefix to generate its name. The resulting {@code Path} is associated928* with the same {@code FileSystem} as the given directory.929*930* <p> The details as to how the name of the directory is constructed is931* implementation dependent and therefore not specified. Where possible932* the {@code prefix} is used to construct candidate names.933*934* <p> As with the {@code createTempFile} methods, this method is only935* part of a temporary-file facility. A {@link Runtime#addShutdownHook936* shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be937* used to delete the directory automatically.938*939* <p> The {@code attrs} parameter is optional {@link FileAttribute940* file-attributes} to set atomically when creating the directory. Each941* attribute is identified by its {@link FileAttribute#name name}. If more942* than one attribute of the same name is included in the array then all but943* the last occurrence is ignored.944*945* @param dir946* the path to directory in which to create the directory947* @param prefix948* the prefix string to be used in generating the directory's name;949* may be {@code null}950* @param attrs951* an optional list of file attributes to set atomically when952* creating the directory953*954* @return the path to the newly created directory that did not exist before955* this method was invoked956*957* @throws IllegalArgumentException958* if the prefix cannot be used to generate a candidate directory name959* @throws UnsupportedOperationException960* if the array contains an attribute that cannot be set atomically961* when creating the directory962* @throws IOException963* if an I/O error occurs or {@code dir} does not exist964* @throws SecurityException965* In the case of the default provider, and a security manager is966* installed, the {@link SecurityManager#checkWrite(String) checkWrite}967* method is invoked to check write access when creating the968* directory.969*/970public static Path createTempDirectory(Path dir,971String prefix,972FileAttribute<?>... attrs)973throws IOException974{975return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir),976prefix, attrs);977}978979/**980* Creates a new directory in the default temporary-file directory, using981* the given prefix to generate its name. The resulting {@code Path} is982* associated with the default {@code FileSystem}.983*984* <p> This method works in exactly the manner specified by {@link985* #createTempDirectory(Path,String,FileAttribute[])} method for the case986* that the {@code dir} parameter is the temporary-file directory.987*988* @param prefix989* the prefix string to be used in generating the directory's name;990* may be {@code null}991* @param attrs992* an optional list of file attributes to set atomically when993* creating the directory994*995* @return the path to the newly created directory that did not exist before996* this method was invoked997*998* @throws IllegalArgumentException999* if the prefix cannot be used to generate a candidate directory name1000* @throws UnsupportedOperationException1001* if the array contains an attribute that cannot be set atomically1002* when creating the directory1003* @throws IOException1004* if an I/O error occurs or the temporary-file directory does not1005* exist1006* @throws SecurityException1007* In the case of the default provider, and a security manager is1008* installed, the {@link SecurityManager#checkWrite(String) checkWrite}1009* method is invoked to check write access when creating the1010* directory.1011*/1012public static Path createTempDirectory(String prefix,1013FileAttribute<?>... attrs)1014throws IOException1015{1016return TempFileHelper.createTempDirectory(null, prefix, attrs);1017}10181019/**1020* Creates a symbolic link to a target <i>(optional operation)</i>.1021*1022* <p> The {@code target} parameter is the target of the link. It may be an1023* {@link Path#isAbsolute absolute} or relative path and may not exist. When1024* the target is a relative path then file system operations on the resulting1025* link are relative to the path of the link.1026*1027* <p> The {@code attrs} parameter is optional {@link FileAttribute1028* attributes} to set atomically when creating the link. Each attribute is1029* identified by its {@link FileAttribute#name name}. If more than one attribute1030* of the same name is included in the array then all but the last occurrence1031* is ignored.1032*1033* <p> Where symbolic links are supported, but the underlying {@link FileStore}1034* does not support symbolic links, then this may fail with an {@link1035* IOException}. Additionally, some operating systems may require that the1036* Java virtual machine be started with implementation specific privileges to1037* create symbolic links, in which case this method may throw {@code IOException}.1038*1039* @param link1040* the path of the symbolic link to create1041* @param target1042* the target of the symbolic link1043* @param attrs1044* the array of attributes to set atomically when creating the1045* symbolic link1046*1047* @return the path to the symbolic link1048*1049* @throws UnsupportedOperationException1050* if the implementation does not support symbolic links or the1051* array contains an attribute that cannot be set atomically when1052* creating the symbolic link1053* @throws FileAlreadyExistsException1054* if a file with the name already exists <i>(optional specific1055* exception)</i>1056* @throws IOException1057* if an I/O error occurs1058* @throws SecurityException1059* In the case of the default provider, and a security manager1060* is installed, it denies {@link LinkPermission}{@code ("symbolic")}1061* or its {@link SecurityManager#checkWrite(String) checkWrite}1062* method denies write access to the path of the symbolic link.1063*/1064public static Path createSymbolicLink(Path link, Path target,1065FileAttribute<?>... attrs)1066throws IOException1067{1068provider(link).createSymbolicLink(link, target, attrs);1069return link;1070}10711072/**1073* Creates a new link (directory entry) for an existing file <i>(optional1074* operation)</i>.1075*1076* <p> The {@code link} parameter locates the directory entry to create.1077* The {@code existing} parameter is the path to an existing file. This1078* method creates a new directory entry for the file so that it can be1079* accessed using {@code link} as the path. On some file systems this is1080* known as creating a "hard link". Whether the file attributes are1081* maintained for the file or for each directory entry is file system1082* specific and therefore not specified. Typically, a file system requires1083* that all links (directory entries) for a file be on the same file system.1084* Furthermore, on some platforms, the Java virtual machine may require to1085* be started with implementation specific privileges to create hard links1086* or to create links to directories.1087*1088* @param link1089* the link (directory entry) to create1090* @param existing1091* a path to an existing file1092*1093* @return the path to the link (directory entry)1094*1095* @throws UnsupportedOperationException1096* if the implementation does not support adding an existing file1097* to a directory1098* @throws FileAlreadyExistsException1099* if the entry could not otherwise be created because a file of1100* that name already exists <i>(optional specific exception)</i>1101* @throws IOException1102* if an I/O error occurs1103* @throws SecurityException1104* In the case of the default provider, and a security manager1105* is installed, it denies {@link LinkPermission}{@code ("hard")}1106* or its {@link SecurityManager#checkWrite(String) checkWrite}1107* method denies write access to either the link or the1108* existing file.1109*/1110public static Path createLink(Path link, Path existing) throws IOException {1111provider(link).createLink(link, existing);1112return link;1113}11141115/**1116* Deletes a file.1117*1118* <p> An implementation may require to examine the file to determine if the1119* file is a directory. Consequently this method may not be atomic with respect1120* to other file system operations. If the file is a symbolic link then the1121* symbolic link itself, not the final target of the link, is deleted.1122*1123* <p> If the file is a directory then the directory must be empty. In some1124* implementations a directory has entries for special files or links that1125* are created when the directory is created. In such implementations a1126* directory is considered empty when only the special entries exist.1127* This method can be used with the {@link #walkFileTree walkFileTree}1128* method to delete a directory and all entries in the directory, or an1129* entire <i>file-tree</i> where required.1130*1131* <p> On some operating systems it may not be possible to remove a file when1132* it is open and in use by this Java virtual machine or other programs.1133*1134* @param path1135* the path to the file to delete1136*1137* @throws NoSuchFileException1138* if the file does not exist <i>(optional specific exception)</i>1139* @throws DirectoryNotEmptyException1140* if the file is a directory and could not otherwise be deleted1141* because the directory is not empty <i>(optional specific1142* exception)</i>1143* @throws IOException1144* if an I/O error occurs1145* @throws SecurityException1146* In the case of the default provider, and a security manager is1147* installed, the {@link SecurityManager#checkDelete(String)} method1148* is invoked to check delete access to the file1149*/1150public static void delete(Path path) throws IOException {1151provider(path).delete(path);1152}11531154/**1155* Deletes a file if it exists.1156*1157* <p> As with the {@link #delete(Path) delete(Path)} method, an1158* implementation may need to examine the file to determine if the file is a1159* directory. Consequently this method may not be atomic with respect to1160* other file system operations. If the file is a symbolic link, then the1161* symbolic link itself, not the final target of the link, is deleted.1162*1163* <p> If the file is a directory then the directory must be empty. In some1164* implementations a directory has entries for special files or links that1165* are created when the directory is created. In such implementations a1166* directory is considered empty when only the special entries exist.1167*1168* <p> On some operating systems it may not be possible to remove a file when1169* it is open and in use by this Java virtual machine or other programs.1170*1171* @param path1172* the path to the file to delete1173*1174* @return {@code true} if the file was deleted by this method; {@code1175* false} if the file could not be deleted because it did not1176* exist1177*1178* @throws DirectoryNotEmptyException1179* if the file is a directory and could not otherwise be deleted1180* because the directory is not empty <i>(optional specific1181* exception)</i>1182* @throws IOException1183* if an I/O error occurs1184* @throws SecurityException1185* In the case of the default provider, and a security manager is1186* installed, the {@link SecurityManager#checkDelete(String)} method1187* is invoked to check delete access to the file.1188*/1189public static boolean deleteIfExists(Path path) throws IOException {1190return provider(path).deleteIfExists(path);1191}11921193// -- Copying and moving files --11941195/**1196* Copy a file to a target file.1197*1198* <p> This method copies a file to the target file with the {@code1199* options} parameter specifying how the copy is performed. By default, the1200* copy fails if the target file already exists or is a symbolic link,1201* except if the source and target are the {@link #isSameFile same} file, in1202* which case the method completes without copying the file. File attributes1203* are not required to be copied to the target file. If symbolic links are1204* supported, and the file is a symbolic link, then the final target of the1205* link is copied. If the file is a directory then it creates an empty1206* directory in the target location (entries in the directory are not1207* copied). This method can be used with the {@link #walkFileTree1208* walkFileTree} method to copy a directory and all entries in the directory,1209* or an entire <i>file-tree</i> where required.1210*1211* <p> The {@code options} parameter may include any of the following:1212*1213* <table class="striped">1214* <caption style="display:none">Options</caption>1215* <thead>1216* <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>1217* </thead>1218* <tbody>1219* <tr>1220* <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th>1221* <td> If the target file exists, then the target file is replaced if it1222* is not a non-empty directory. If the target file exists and is a1223* symbolic link, then the symbolic link itself, not the target of1224* the link, is replaced. </td>1225* </tr>1226* <tr>1227* <th scope="row"> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </th>1228* <td> Attempts to copy the file attributes associated with this file to1229* the target file. The exact file attributes that are copied is platform1230* and file system dependent and therefore unspecified. Minimally, the1231* {@link BasicFileAttributes#lastModifiedTime last-modified-time} is1232* copied to the target file if supported by both the source and target1233* file stores. Copying of file timestamps may result in precision1234* loss. </td>1235* </tr>1236* <tr>1237* <th scope="row"> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </th>1238* <td> Symbolic links are not followed. If the file is a symbolic link,1239* then the symbolic link itself, not the target of the link, is copied.1240* It is implementation specific if file attributes can be copied to the1241* new link. In other words, the {@code COPY_ATTRIBUTES} option may be1242* ignored when copying a symbolic link. </td>1243* </tr>1244* </tbody>1245* </table>1246*1247* <p> An implementation of this interface may support additional1248* implementation specific options.1249*1250* <p> Copying a file is not an atomic operation. If an {@link IOException}1251* is thrown, then it is possible that the target file is incomplete or some1252* of its file attributes have not been copied from the source file. When1253* the {@code REPLACE_EXISTING} option is specified and the target file1254* exists, then the target file is replaced. The check for the existence of1255* the file and the creation of the new file may not be atomic with respect1256* to other file system activities.1257*1258* <p> <b>Usage Example:</b>1259* Suppose we want to copy a file into a directory, giving it the same file1260* name as the source file:1261* <pre>1262* Path source = ...1263* Path newdir = ...1264* Files.copy(source, newdir.resolve(source.getFileName());1265* </pre>1266*1267* @param source1268* the path to the file to copy1269* @param target1270* the path to the target file (may be associated with a different1271* provider to the source path)1272* @param options1273* options specifying how the copy should be done1274*1275* @return the path to the target file1276*1277* @throws UnsupportedOperationException1278* if the array contains a copy option that is not supported1279* @throws FileAlreadyExistsException1280* if the target file exists but cannot be replaced because the1281* {@code REPLACE_EXISTING} option is not specified <i>(optional1282* specific exception)</i>1283* @throws DirectoryNotEmptyException1284* the {@code REPLACE_EXISTING} option is specified but the file1285* cannot be replaced because it is a non-empty directory1286* <i>(optional specific exception)</i>1287* @throws IOException1288* if an I/O error occurs1289* @throws SecurityException1290* In the case of the default provider, and a security manager is1291* installed, the {@link SecurityManager#checkRead(String) checkRead}1292* method is invoked to check read access to the source file, the1293* {@link SecurityManager#checkWrite(String) checkWrite} is invoked1294* to check write access to the target file. If a symbolic link is1295* copied the security manager is invoked to check {@link1296* LinkPermission}{@code ("symbolic")}.1297*/1298public static Path copy(Path source, Path target, CopyOption... options)1299throws IOException1300{1301FileSystemProvider provider = provider(source);1302if (provider(target) == provider) {1303// same provider1304provider.copy(source, target, options);1305} else {1306// different providers1307CopyMoveHelper.copyToForeignTarget(source, target, options);1308}1309return target;1310}13111312/**1313* Move or rename a file to a target file.1314*1315* <p> By default, this method attempts to move the file to the target1316* file, failing if the target file exists except if the source and1317* target are the {@link #isSameFile same} file, in which case this method1318* has no effect. If the file is a symbolic link then the symbolic link1319* itself, not the target of the link, is moved. This method may be1320* invoked to move an empty directory. In some implementations a directory1321* has entries for special files or links that are created when the1322* directory is created. In such implementations a directory is considered1323* empty when only the special entries exist. When invoked to move a1324* directory that is not empty then the directory is moved if it does not1325* require moving the entries in the directory. For example, renaming a1326* directory on the same {@link FileStore} will usually not require moving1327* the entries in the directory. When moving a directory requires that its1328* entries be moved then this method fails (by throwing an {@code1329* IOException}). To move a <i>file tree</i> may involve copying rather1330* than moving directories and this can be done using the {@link1331* #copy copy} method in conjunction with the {@link1332* #walkFileTree Files.walkFileTree} utility method.1333*1334* <p> The {@code options} parameter may include any of the following:1335*1336* <table class="striped">1337* <caption style="display:none">Options</caption>1338* <thead>1339* <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>1340* </thead>1341* <tbody>1342* <tr>1343* <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th>1344* <td> If the target file exists, then the target file is replaced if it1345* is not a non-empty directory. If the target file exists and is a1346* symbolic link, then the symbolic link itself, not the target of1347* the link, is replaced. </td>1348* </tr>1349* <tr>1350* <th scope="row"> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </th>1351* <td> The move is performed as an atomic file system operation and all1352* other options are ignored. If the target file exists then it is1353* implementation specific if the existing file is replaced or this method1354* fails by throwing an {@link IOException}. If the move cannot be1355* performed as an atomic file system operation then {@link1356* AtomicMoveNotSupportedException} is thrown. This can arise, for1357* example, when the target location is on a different {@code FileStore}1358* and would require that the file be copied, or target location is1359* associated with a different provider to this object. </td>1360* </tbody>1361* </table>1362*1363* <p> An implementation of this interface may support additional1364* implementation specific options.1365*1366* <p> Moving a file will copy the {@link1367* BasicFileAttributes#lastModifiedTime last-modified-time} to the target1368* file if supported by both source and target file stores. Copying of file1369* timestamps may result in precision loss. An implementation may also1370* attempt to copy other file attributes but is not required to fail if the1371* file attributes cannot be copied. When the move is performed as1372* a non-atomic operation, and an {@code IOException} is thrown, then the1373* state of the files is not defined. The original file and the target file1374* may both exist, the target file may be incomplete or some of its file1375* attributes may not been copied from the original file.1376*1377* <p> <b>Usage Examples:</b>1378* Suppose we want to rename a file to "newname", keeping the file in the1379* same directory:1380* <pre>1381* Path source = ...1382* Files.move(source, source.resolveSibling("newname"));1383* </pre>1384* Alternatively, suppose we want to move a file to new directory, keeping1385* the same file name, and replacing any existing file of that name in the1386* directory:1387* <pre>1388* Path source = ...1389* Path newdir = ...1390* Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);1391* </pre>1392*1393* @param source1394* the path to the file to move1395* @param target1396* the path to the target file (may be associated with a different1397* provider to the source path)1398* @param options1399* options specifying how the move should be done1400*1401* @return the path to the target file1402*1403* @throws UnsupportedOperationException1404* if the array contains a copy option that is not supported1405* @throws FileAlreadyExistsException1406* if the target file exists but cannot be replaced because the1407* {@code REPLACE_EXISTING} option is not specified <i>(optional1408* specific exception)</i>1409* @throws DirectoryNotEmptyException1410* the {@code REPLACE_EXISTING} option is specified but the file1411* cannot be replaced because it is a non-empty directory, or the1412* source is a non-empty directory containing entries that would1413* be required to be moved <i>(optional specific exceptions)</i>1414* @throws AtomicMoveNotSupportedException1415* if the options array contains the {@code ATOMIC_MOVE} option but1416* the file cannot be moved as an atomic file system operation.1417* @throws IOException1418* if an I/O error occurs1419* @throws SecurityException1420* In the case of the default provider, and a security manager is1421* installed, the {@link SecurityManager#checkWrite(String) checkWrite}1422* method is invoked to check write access to both the source and1423* target file.1424*/1425public static Path move(Path source, Path target, CopyOption... options)1426throws IOException1427{1428FileSystemProvider provider = provider(source);1429if (provider(target) == provider) {1430// same provider1431provider.move(source, target, options);1432} else {1433// different providers1434CopyMoveHelper.moveToForeignTarget(source, target, options);1435}1436return target;1437}14381439// -- Miscellaneous --14401441/**1442* Reads the target of a symbolic link <i>(optional operation)</i>.1443*1444* <p> If the file system supports <a href="package-summary.html#links">symbolic1445* links</a> then this method is used to read the target of the link, failing1446* if the file is not a symbolic link. The target of the link need not exist.1447* The returned {@code Path} object will be associated with the same file1448* system as {@code link}.1449*1450* @param link1451* the path to the symbolic link1452*1453* @return a {@code Path} object representing the target of the link1454*1455* @throws UnsupportedOperationException1456* if the implementation does not support symbolic links1457* @throws NotLinkException1458* if the target could otherwise not be read because the file1459* is not a symbolic link <i>(optional specific exception)</i>1460* @throws IOException1461* if an I/O error occurs1462* @throws SecurityException1463* In the case of the default provider, and a security manager1464* is installed, it checks that {@code FilePermission} has been1465* granted with the "{@code readlink}" action to read the link.1466*/1467public static Path readSymbolicLink(Path link) throws IOException {1468return provider(link).readSymbolicLink(link);1469}14701471/**1472* Returns the {@link FileStore} representing the file store where a file1473* is located.1474*1475* <p> Once a reference to the {@code FileStore} is obtained it is1476* implementation specific if operations on the returned {@code FileStore},1477* or {@link FileStoreAttributeView} objects obtained from it, continue1478* to depend on the existence of the file. In particular the behavior is not1479* defined for the case that the file is deleted or moved to a different1480* file store.1481*1482* @param path1483* the path to the file1484*1485* @return the file store where the file is stored1486*1487* @throws IOException1488* if an I/O error occurs1489* @throws SecurityException1490* In the case of the default provider, and a security manager is1491* installed, the {@link SecurityManager#checkRead(String) checkRead}1492* method is invoked to check read access to the file, and in1493* addition it checks1494* {@link RuntimePermission}{@code ("getFileStoreAttributes")}1495*/1496public static FileStore getFileStore(Path path) throws IOException {1497return provider(path).getFileStore(path);1498}14991500/**1501* Tests if two paths locate the same file.1502*1503* <p> If both {@code Path} objects are {@link Path#equals(Object) equal}1504* then this method returns {@code true} without checking if the file exists.1505* If the two {@code Path} objects are associated with different providers1506* then this method returns {@code false}. Otherwise, this method checks if1507* both {@code Path} objects locate the same file, and depending on the1508* implementation, may require to open or access both files.1509*1510* <p> If the file system and files remain static, then this method implements1511* an equivalence relation for non-null {@code Paths}.1512* <ul>1513* <li>It is <i>reflexive</i>: for {@code Path} {@code f},1514* {@code isSameFile(f,f)} should return {@code true}.1515* <li>It is <i>symmetric</i>: for two {@code Paths} {@code f} and {@code g},1516* {@code isSameFile(f,g)} will equal {@code isSameFile(g,f)}.1517* <li>It is <i>transitive</i>: for three {@code Paths}1518* {@code f}, {@code g}, and {@code h}, if {@code isSameFile(f,g)} returns1519* {@code true} and {@code isSameFile(g,h)} returns {@code true}, then1520* {@code isSameFile(f,h)} will return {@code true}.1521* </ul>1522*1523* @param path1524* one path to the file1525* @param path21526* the other path1527*1528* @return {@code true} if, and only if, the two paths locate the same file1529*1530* @throws IOException1531* if an I/O error occurs1532* @throws SecurityException1533* In the case of the default provider, and a security manager is1534* installed, the {@link SecurityManager#checkRead(String) checkRead}1535* method is invoked to check read access to both files.1536*1537* @see java.nio.file.attribute.BasicFileAttributes#fileKey1538*/1539public static boolean isSameFile(Path path, Path path2) throws IOException {1540return provider(path).isSameFile(path, path2);1541}15421543/**1544* Finds and returns the position of the first mismatched byte in the content1545* of two files, or {@code -1L} if there is no mismatch. The position will be1546* in the inclusive range of {@code 0L} up to the size (in bytes) of the1547* smaller file.1548*1549* <p> Two files are considered to match if they satisfy one of the following1550* conditions:1551* <ul>1552* <li> The two paths locate the {@linkplain #isSameFile(Path, Path) same file},1553* even if two {@linkplain Path#equals(Object) equal} paths locate a file1554* does not exist, or </li>1555* <li> The two files are the same size, and every byte in the first file1556* is identical to the corresponding byte in the second file. </li>1557* </ul>1558*1559* <p> Otherwise there is a mismatch between the two files and the value1560* returned by this method is:1561* <ul>1562* <li> The position of the first mismatched byte, or </li>1563* <li> The size of the smaller file (in bytes) when the files are different1564* sizes and every byte of the smaller file is identical to the1565* corresponding byte of the larger file. </li>1566* </ul>1567*1568* <p> This method may not be atomic with respect to other file system1569* operations. This method is always <i>reflexive</i> (for {@code Path f},1570* {@code mismatch(f,f)} returns {@code -1L}). If the file system and files1571* remain static, then this method is <i>symmetric</i> (for two {@code Paths f}1572* and {@code g}, {@code mismatch(f,g)} will return the same value as1573* {@code mismatch(g,f)}).1574*1575* @param path1576* the path to the first file1577* @param path21578* the path to the second file1579*1580* @return the position of the first mismatch or {@code -1L} if no mismatch1581*1582* @throws IOException1583* if an I/O error occurs1584* @throws SecurityException1585* In the case of the default provider, and a security manager is1586* installed, the {@link SecurityManager#checkRead(String) checkRead}1587* method is invoked to check read access to both files.1588*1589* @since 121590*/1591public static long mismatch(Path path, Path path2) throws IOException {1592if (isSameFile(path, path2)) {1593return -1;1594}1595byte[] buffer1 = new byte[BUFFER_SIZE];1596byte[] buffer2 = new byte[BUFFER_SIZE];1597try (InputStream in1 = Files.newInputStream(path);1598InputStream in2 = Files.newInputStream(path2);) {1599long totalRead = 0;1600while (true) {1601int nRead1 = in1.readNBytes(buffer1, 0, BUFFER_SIZE);1602int nRead2 = in2.readNBytes(buffer2, 0, BUFFER_SIZE);16031604int i = Arrays.mismatch(buffer1, 0, nRead1, buffer2, 0, nRead2);1605if (i > -1) {1606return totalRead + i;1607}1608if (nRead1 < BUFFER_SIZE) {1609// we've reached the end of the files, but found no mismatch1610return -1;1611}1612totalRead += nRead1;1613}1614}1615}16161617/**1618* Tells whether or not a file is considered <em>hidden</em>.1619*1620* @apiNote1621* The exact definition of hidden is platform or provider dependent. On UNIX1622* for example a file is considered to be hidden if its name begins with a1623* period character ('.'). On Windows a file is considered hidden if the DOS1624* {@link DosFileAttributes#isHidden hidden} attribute is set.1625*1626* <p> Depending on the implementation this method may require to access1627* the file system to determine if the file is considered hidden.1628*1629* @param path1630* the path to the file to test1631*1632* @return {@code true} if the file is considered hidden1633*1634* @throws IOException1635* if an I/O error occurs1636* @throws SecurityException1637* In the case of the default provider, and a security manager is1638* installed, the {@link SecurityManager#checkRead(String) checkRead}1639* method is invoked to check read access to the file.1640*/1641public static boolean isHidden(Path path) throws IOException {1642return provider(path).isHidden(path);1643}16441645// lazy loading of default and installed file type detectors1646private static class FileTypeDetectors{1647static final FileTypeDetector defaultFileTypeDetector =1648createDefaultFileTypeDetector();1649static final List<FileTypeDetector> installedDetectors =1650loadInstalledDetectors();16511652// creates the default file type detector1653@SuppressWarnings("removal")1654private static FileTypeDetector createDefaultFileTypeDetector() {1655return AccessController1656.doPrivileged(new PrivilegedAction<>() {1657@Override public FileTypeDetector run() {1658return sun.nio.fs.DefaultFileTypeDetector.create();1659}});1660}16611662// loads all installed file type detectors1663@SuppressWarnings("removal")1664private static List<FileTypeDetector> loadInstalledDetectors() {1665return AccessController1666.doPrivileged(new PrivilegedAction<>() {1667@Override public List<FileTypeDetector> run() {1668List<FileTypeDetector> list = new ArrayList<>();1669ServiceLoader<FileTypeDetector> loader = ServiceLoader1670.load(FileTypeDetector.class, ClassLoader.getSystemClassLoader());1671for (FileTypeDetector detector: loader) {1672list.add(detector);1673}1674return list;1675}});1676}1677}16781679/**1680* Probes the content type of a file.1681*1682* <p> This method uses the installed {@link FileTypeDetector} implementations1683* to probe the given file to determine its content type. Each file type1684* detector's {@link FileTypeDetector#probeContentType probeContentType} is1685* invoked, in turn, to probe the file type. If the file is recognized then1686* the content type is returned. If the file is not recognized by any of the1687* installed file type detectors then a system-default file type detector is1688* invoked to guess the content type.1689*1690* <p> A given invocation of the Java virtual machine maintains a system-wide1691* list of file type detectors. Installed file type detectors are loaded1692* using the service-provider loading facility defined by the {@link ServiceLoader}1693* class. Installed file type detectors are loaded using the system class1694* loader. If the system class loader cannot be found then the platform class1695* loader is used. File type detectors are typically installed1696* by placing them in a JAR file on the application class path,1697* the JAR file contains a provider-configuration file1698* named {@code java.nio.file.spi.FileTypeDetector} in the resource directory1699* {@code META-INF/services}, and the file lists one or more fully-qualified1700* names of concrete subclass of {@code FileTypeDetector } that have a zero1701* argument constructor. If the process of locating or instantiating the1702* installed file type detectors fails then an unspecified error is thrown.1703* The ordering that installed providers are located is implementation1704* specific.1705*1706* <p> The return value of this method is the string form of the value of a1707* Multipurpose Internet Mail Extension (MIME) content type as1708* defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045:1709* Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet1710* Message Bodies</i></a>. The string is guaranteed to be parsable according1711* to the grammar in the RFC.1712*1713* @param path1714* the path to the file to probe1715*1716* @return The content type of the file, or {@code null} if the content1717* type cannot be determined1718*1719* @throws IOException1720* if an I/O error occurs1721* @throws SecurityException1722* If a security manager is installed and it denies an unspecified1723* permission required by a file type detector implementation.1724*/1725public static String probeContentType(Path path)1726throws IOException1727{1728// try installed file type detectors1729for (FileTypeDetector detector: FileTypeDetectors.installedDetectors) {1730String result = detector.probeContentType(path);1731if (result != null)1732return result;1733}17341735// fallback to default1736return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path);1737}17381739// -- File Attributes --17401741/**1742* Returns a file attribute view of a given type.1743*1744* <p> A file attribute view provides a read-only or updatable view of a1745* set of file attributes. This method is intended to be used where the file1746* attribute view defines type-safe methods to read or update the file1747* attributes. The {@code type} parameter is the type of the attribute view1748* required and the method returns an instance of that type if supported.1749* The {@link BasicFileAttributeView} type supports access to the basic1750* attributes of a file. Invoking this method to select a file attribute1751* view of that type will always return an instance of that class.1752*1753* <p> The {@code options} array may be used to indicate how symbolic links1754* are handled by the resulting file attribute view for the case that the1755* file is a symbolic link. By default, symbolic links are followed. If the1756* option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then1757* symbolic links are not followed. This option is ignored by implementations1758* that do not support symbolic links.1759*1760* <p> <b>Usage Example:</b>1761* Suppose we want read or set a file's ACL, if supported:1762* <pre>1763* Path path = ...1764* AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);1765* if (view != null) {1766* List<AclEntry> acl = view.getAcl();1767* :1768* }1769* </pre>1770*1771* @param <V>1772* The {@code FileAttributeView} type1773* @param path1774* the path to the file1775* @param type1776* the {@code Class} object corresponding to the file attribute view1777* @param options1778* options indicating how symbolic links are handled1779*1780* @return a file attribute view of the specified type, or {@code null} if1781* the attribute view type is not available1782*/1783public static <V extends FileAttributeView> V getFileAttributeView(Path path,1784Class<V> type,1785LinkOption... options)1786{1787return provider(path).getFileAttributeView(path, type, options);1788}17891790/**1791* Reads a file's attributes as a bulk operation.1792*1793* <p> The {@code type} parameter is the type of the attributes required1794* and this method returns an instance of that type if supported. All1795* implementations support a basic set of file attributes and so invoking1796* this method with a {@code type} parameter of {@code1797* BasicFileAttributes.class} will not throw {@code1798* UnsupportedOperationException}.1799*1800* <p> The {@code options} array may be used to indicate how symbolic links1801* are handled for the case that the file is a symbolic link. By default,1802* symbolic links are followed and the file attribute of the final target1803* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1804* NOFOLLOW_LINKS} is present then symbolic links are not followed.1805*1806* <p> It is implementation specific if all file attributes are read as an1807* atomic operation with respect to other file system operations.1808*1809* <p> <b>Usage Example:</b>1810* Suppose we want to read a file's attributes in bulk:1811* <pre>1812* Path path = ...1813* BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);1814* </pre>1815* Alternatively, suppose we want to read file's POSIX attributes without1816* following symbolic links:1817* <pre>1818* PosixFileAttributes attrs =1819* Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS);1820* </pre>1821*1822* @param <A>1823* The {@code BasicFileAttributes} type1824* @param path1825* the path to the file1826* @param type1827* the {@code Class} of the file attributes required1828* to read1829* @param options1830* options indicating how symbolic links are handled1831*1832* @return the file attributes1833*1834* @throws UnsupportedOperationException1835* if an attributes of the given type are not supported1836* @throws IOException1837* if an I/O error occurs1838* @throws SecurityException1839* In the case of the default provider, a security manager is1840* installed, its {@link SecurityManager#checkRead(String) checkRead}1841* method is invoked to check read access to the file. If this1842* method is invoked to read security sensitive attributes then the1843* security manager may be invoke to check for additional permissions.1844*/1845public static <A extends BasicFileAttributes> A readAttributes(Path path,1846Class<A> type,1847LinkOption... options)1848throws IOException1849{1850return provider(path).readAttributes(path, type, options);1851}18521853/**1854* Sets the value of a file attribute.1855*1856* <p> The {@code attribute} parameter identifies the attribute to be set1857* and takes the form:1858* <blockquote>1859* [<i>view-name</i><b>:</b>]<i>attribute-name</i>1860* </blockquote>1861* where square brackets [...] delineate an optional component and the1862* character {@code ':'} stands for itself.1863*1864* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link1865* FileAttributeView} that identifies a set of file attributes. If not1866* specified then it defaults to {@code "basic"}, the name of the file1867* attribute view that identifies the basic set of file attributes common to1868* many file systems. <i>attribute-name</i> is the name of the attribute1869* within the set.1870*1871* <p> The {@code options} array may be used to indicate how symbolic links1872* are handled for the case that the file is a symbolic link. By default,1873* symbolic links are followed and the file attribute of the final target1874* of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS1875* NOFOLLOW_LINKS} is present then symbolic links are not followed.1876*1877* <p> <b>Usage Example:</b>1878* Suppose we want to set the DOS "hidden" attribute:1879* <pre>1880* Path path = ...1881* Files.setAttribute(path, "dos:hidden", true);1882* </pre>1883*1884* @param path1885* the path to the file1886* @param attribute1887* the attribute to set1888* @param value1889* the attribute value1890* @param options1891* options indicating how symbolic links are handled1892*1893* @return the given path1894*1895* @throws UnsupportedOperationException1896* if the attribute view is not available1897* @throws IllegalArgumentException1898* if the attribute name is not specified, or is not recognized, or1899* the attribute value is of the correct type but has an1900* inappropriate value1901* @throws ClassCastException1902* if the attribute value is not of the expected type or is a1903* collection containing elements that are not of the expected1904* type1905* @throws IOException1906* if an I/O error occurs1907* @throws SecurityException1908* In the case of the default provider, and a security manager is1909* installed, its {@link SecurityManager#checkWrite(String) checkWrite}1910* method denies write access to the file. If this method is invoked1911* to set security sensitive attributes then the security manager1912* may be invoked to check for additional permissions.1913*/1914public static Path setAttribute(Path path, String attribute, Object value,1915LinkOption... options)1916throws IOException1917{1918provider(path).setAttribute(path, attribute, value, options);1919return path;1920}19211922/**1923* Reads the value of a file attribute.1924*1925* <p> The {@code attribute} parameter identifies the attribute to be read1926* and takes the form:1927* <blockquote>1928* [<i>view-name</i><b>:</b>]<i>attribute-name</i>1929* </blockquote>1930* where square brackets [...] delineate an optional component and the1931* character {@code ':'} stands for itself.1932*1933* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link1934* FileAttributeView} that identifies a set of file attributes. If not1935* specified then it defaults to {@code "basic"}, the name of the file1936* attribute view that identifies the basic set of file attributes common to1937* many file systems. <i>attribute-name</i> is the name of the attribute.1938*1939* <p> The {@code options} array may be used to indicate how symbolic links1940* are handled for the case that the file is a symbolic link. By default,1941* symbolic links are followed and the file attribute of the final target1942* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS1943* NOFOLLOW_LINKS} is present then symbolic links are not followed.1944*1945* <p> <b>Usage Example:</b>1946* Suppose we require the user ID of the file owner on a system that1947* supports a "{@code unix}" view:1948* <pre>1949* Path path = ...1950* int uid = (Integer)Files.getAttribute(path, "unix:uid");1951* </pre>1952*1953* @param path1954* the path to the file1955* @param attribute1956* the attribute to read1957* @param options1958* options indicating how symbolic links are handled1959*1960* @return the attribute value1961*1962* @throws UnsupportedOperationException1963* if the attribute view is not available1964* @throws IllegalArgumentException1965* if the attribute name is not specified or is not recognized1966* @throws IOException1967* if an I/O error occurs1968* @throws SecurityException1969* In the case of the default provider, and a security manager is1970* installed, its {@link SecurityManager#checkRead(String) checkRead}1971* method denies read access to the file. If this method is invoked1972* to read security sensitive attributes then the security manager1973* may be invoked to check for additional permissions.1974*/1975public static Object getAttribute(Path path, String attribute,1976LinkOption... options)1977throws IOException1978{1979// only one attribute should be read1980if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0)1981throw new IllegalArgumentException(attribute);1982Map<String,Object> map = readAttributes(path, attribute, options);1983assert map.size() == 1;1984String name;1985int pos = attribute.indexOf(':');1986if (pos == -1) {1987name = attribute;1988} else {1989name = (pos == attribute.length()) ? "" : attribute.substring(pos+1);1990}1991return map.get(name);1992}19931994/**1995* Reads a set of file attributes as a bulk operation.1996*1997* <p> The {@code attributes} parameter identifies the attributes to be read1998* and takes the form:1999* <blockquote>2000* [<i>view-name</i><b>:</b>]<i>attribute-list</i>2001* </blockquote>2002* where square brackets [...] delineate an optional component and the2003* character {@code ':'} stands for itself.2004*2005* <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link2006* FileAttributeView} that identifies a set of file attributes. If not2007* specified then it defaults to {@code "basic"}, the name of the file2008* attribute view that identifies the basic set of file attributes common to2009* many file systems.2010*2011* <p> The <i>attribute-list</i> component is a comma separated list of2012* one or more names of attributes to read. If the list contains the value2013* {@code "*"} then all attributes are read. Attributes that are not supported2014* are ignored and will not be present in the returned map. It is2015* implementation specific if all attributes are read as an atomic operation2016* with respect to other file system operations.2017*2018* <p> The following examples demonstrate possible values for the {@code2019* attributes} parameter:2020*2021* <table class="striped" style="text-align: left; margin-left:2em">2022* <caption style="display:none">Possible values</caption>2023* <thead>2024* <tr>2025* <th scope="col">Example2026* <th scope="col">Description2027* </thead>2028* <tbody>2029* <tr>2030* <th scope="row"> {@code "*"} </th>2031* <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td>2032* </tr>2033* <tr>2034* <th scope="row"> {@code "size,lastModifiedTime,lastAccessTime"} </th>2035* <td> Reads the file size, last modified time, and last access time2036* attributes. </td>2037* </tr>2038* <tr>2039* <th scope="row"> {@code "posix:*"} </th>2040* <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td>2041* </tr>2042* <tr>2043* <th scope="row"> {@code "posix:permissions,owner,size"} </th>2044* <td> Reads the POSIX file permissions, owner, and file size. </td>2045* </tr>2046* </tbody>2047* </table>2048*2049* <p> The {@code options} array may be used to indicate how symbolic links2050* are handled for the case that the file is a symbolic link. By default,2051* symbolic links are followed and the file attribute of the final target2052* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2053* NOFOLLOW_LINKS} is present then symbolic links are not followed.2054*2055* @param path2056* the path to the file2057* @param attributes2058* the attributes to read2059* @param options2060* options indicating how symbolic links are handled2061*2062* @return a map of the attributes returned; The map's keys are the2063* attribute names, its values are the attribute values2064*2065* @throws UnsupportedOperationException2066* if the attribute view is not available2067* @throws IllegalArgumentException2068* if no attributes are specified or an unrecognized attribute is2069* specified2070* @throws IOException2071* if an I/O error occurs2072* @throws SecurityException2073* In the case of the default provider, and a security manager is2074* installed, its {@link SecurityManager#checkRead(String) checkRead}2075* method denies read access to the file. If this method is invoked2076* to read security sensitive attributes then the security manager2077* may be invoke to check for additional permissions.2078*/2079public static Map<String,Object> readAttributes(Path path, String attributes,2080LinkOption... options)2081throws IOException2082{2083return provider(path).readAttributes(path, attributes, options);2084}20852086/**2087* Returns a file's POSIX file permissions.2088*2089* <p> The {@code path} parameter is associated with a {@code FileSystem}2090* that supports the {@link PosixFileAttributeView}. This attribute view2091* provides access to file attributes commonly associated with files on file2092* systems used by operating systems that implement the Portable Operating2093* System Interface (POSIX) family of standards.2094*2095* <p> The {@code options} array may be used to indicate how symbolic links2096* are handled for the case that the file is a symbolic link. By default,2097* symbolic links are followed and the file attribute of the final target2098* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2099* NOFOLLOW_LINKS} is present then symbolic links are not followed.2100*2101* @param path2102* the path to the file2103* @param options2104* options indicating how symbolic links are handled2105*2106* @return the file permissions2107*2108* @throws UnsupportedOperationException2109* if the associated file system does not support the {@code2110* PosixFileAttributeView}2111* @throws IOException2112* if an I/O error occurs2113* @throws SecurityException2114* In the case of the default provider, a security manager is2115* installed, and it denies2116* {@link RuntimePermission}{@code ("accessUserInformation")}2117* or its {@link SecurityManager#checkRead(String) checkRead} method2118* denies read access to the file.2119*/2120public static Set<PosixFilePermission> getPosixFilePermissions(Path path,2121LinkOption... options)2122throws IOException2123{2124return readAttributes(path, PosixFileAttributes.class, options).permissions();2125}21262127/**2128* Sets a file's POSIX permissions.2129*2130* <p> The {@code path} parameter is associated with a {@code FileSystem}2131* that supports the {@link PosixFileAttributeView}. This attribute view2132* provides access to file attributes commonly associated with files on file2133* systems used by operating systems that implement the Portable Operating2134* System Interface (POSIX) family of standards.2135*2136* @param path2137* The path to the file2138* @param perms2139* The new set of permissions2140*2141* @return The given path2142*2143* @throws UnsupportedOperationException2144* if the associated file system does not support the {@code2145* PosixFileAttributeView}2146* @throws ClassCastException2147* if the sets contains elements that are not of type {@code2148* PosixFilePermission}2149* @throws IOException2150* if an I/O error occurs2151* @throws SecurityException2152* In the case of the default provider, and a security manager is2153* installed, it denies2154* {@link RuntimePermission}{@code ("accessUserInformation")}2155* or its {@link SecurityManager#checkWrite(String) checkWrite}2156* method denies write access to the file.2157*/2158public static Path setPosixFilePermissions(Path path,2159Set<PosixFilePermission> perms)2160throws IOException2161{2162PosixFileAttributeView view =2163getFileAttributeView(path, PosixFileAttributeView.class);2164if (view == null)2165throw new UnsupportedOperationException();2166view.setPermissions(perms);2167return path;2168}21692170/**2171* Returns the owner of a file.2172*2173* <p> The {@code path} parameter is associated with a file system that2174* supports {@link FileOwnerAttributeView}. This file attribute view provides2175* access to a file attribute that is the owner of the file.2176*2177* @param path2178* The path to the file2179* @param options2180* options indicating how symbolic links are handled2181*2182* @return A user principal representing the owner of the file2183*2184* @throws UnsupportedOperationException2185* if the associated file system does not support the {@code2186* FileOwnerAttributeView}2187* @throws IOException2188* if an I/O error occurs2189* @throws SecurityException2190* In the case of the default provider, and a security manager is2191* installed, it denies2192* {@link RuntimePermission}{@code ("accessUserInformation")}2193* or its {@link SecurityManager#checkRead(String) checkRead} method2194* denies read access to the file.2195*/2196public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException {2197FileOwnerAttributeView view =2198getFileAttributeView(path, FileOwnerAttributeView.class, options);2199if (view == null)2200throw new UnsupportedOperationException();2201return view.getOwner();2202}22032204/**2205* Updates the file owner.2206*2207* <p> The {@code path} parameter is associated with a file system that2208* supports {@link FileOwnerAttributeView}. This file attribute view provides2209* access to a file attribute that is the owner of the file.2210*2211* <p> <b>Usage Example:</b>2212* Suppose we want to make "joe" the owner of a file:2213* <pre>2214* Path path = ...2215* UserPrincipalLookupService lookupService =2216* provider(path).getUserPrincipalLookupService();2217* UserPrincipal joe = lookupService.lookupPrincipalByName("joe");2218* Files.setOwner(path, joe);2219* </pre>2220*2221* @param path2222* The path to the file2223* @param owner2224* The new file owner2225*2226* @return The given path2227*2228* @throws UnsupportedOperationException2229* if the associated file system does not support the {@code2230* FileOwnerAttributeView}2231* @throws IOException2232* if an I/O error occurs2233* @throws SecurityException2234* In the case of the default provider, and a security manager is2235* installed, it denies2236* {@link RuntimePermission}{@code ("accessUserInformation")}2237* or its {@link SecurityManager#checkWrite(String) checkWrite}2238* method denies write access to the file.2239*2240* @see FileSystem#getUserPrincipalLookupService2241* @see java.nio.file.attribute.UserPrincipalLookupService2242*/2243public static Path setOwner(Path path, UserPrincipal owner)2244throws IOException2245{2246FileOwnerAttributeView view =2247getFileAttributeView(path, FileOwnerAttributeView.class);2248if (view == null)2249throw new UnsupportedOperationException();2250view.setOwner(owner);2251return path;2252}22532254/**2255* Tests whether a file is a symbolic link.2256*2257* <p> Where it is required to distinguish an I/O exception from the case2258* that the file is not a symbolic link then the file attributes can be2259* read with the {@link #readAttributes(Path,Class,LinkOption[])2260* readAttributes} method and the file type tested with the {@link2261* BasicFileAttributes#isSymbolicLink} method.2262*2263* @param path The path to the file2264*2265* @return {@code true} if the file is a symbolic link; {@code false} if2266* the file does not exist, is not a symbolic link, or it cannot2267* be determined if the file is a symbolic link or not.2268*2269* @throws SecurityException2270* In the case of the default provider, and a security manager is2271* installed, its {@link SecurityManager#checkRead(String) checkRead}2272* method denies read access to the file.2273*/2274public static boolean isSymbolicLink(Path path) {2275try {2276return readAttributes(path,2277BasicFileAttributes.class,2278LinkOption.NOFOLLOW_LINKS).isSymbolicLink();2279} catch (IOException ioe) {2280return false;2281}2282}22832284/**2285* Tests whether a file is a directory.2286*2287* <p> The {@code options} array may be used to indicate how symbolic links2288* are handled for the case that the file is a symbolic link. By default,2289* symbolic links are followed and the file attribute of the final target2290* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2291* NOFOLLOW_LINKS} is present then symbolic links are not followed.2292*2293* <p> Where it is required to distinguish an I/O exception from the case2294* that the file is not a directory then the file attributes can be2295* read with the {@link #readAttributes(Path,Class,LinkOption[])2296* readAttributes} method and the file type tested with the {@link2297* BasicFileAttributes#isDirectory} method.2298*2299* @param path2300* the path to the file to test2301* @param options2302* options indicating how symbolic links are handled2303*2304* @return {@code true} if the file is a directory; {@code false} if2305* the file does not exist, is not a directory, or it cannot2306* be determined if the file is a directory or not.2307*2308* @throws SecurityException2309* In the case of the default provider, and a security manager is2310* installed, its {@link SecurityManager#checkRead(String) checkRead}2311* method denies read access to the file.2312*/2313public static boolean isDirectory(Path path, LinkOption... options) {2314if (options.length == 0) {2315FileSystemProvider provider = provider(path);2316if (provider instanceof AbstractFileSystemProvider)2317return ((AbstractFileSystemProvider)provider).isDirectory(path);2318}23192320try {2321return readAttributes(path, BasicFileAttributes.class, options).isDirectory();2322} catch (IOException ioe) {2323return false;2324}2325}23262327/**2328* Tests whether a file is a regular file with opaque content.2329*2330* <p> The {@code options} array may be used to indicate how symbolic links2331* are handled for the case that the file is a symbolic link. By default,2332* symbolic links are followed and the file attribute of the final target2333* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2334* NOFOLLOW_LINKS} is present then symbolic links are not followed.2335*2336* <p> Where it is required to distinguish an I/O exception from the case2337* that the file is not a regular file then the file attributes can be2338* read with the {@link #readAttributes(Path,Class,LinkOption[])2339* readAttributes} method and the file type tested with the {@link2340* BasicFileAttributes#isRegularFile} method.2341*2342* @param path2343* the path to the file2344* @param options2345* options indicating how symbolic links are handled2346*2347* @return {@code true} if the file is a regular file; {@code false} if2348* the file does not exist, is not a regular file, or it2349* cannot be determined if the file is a regular file or not.2350*2351* @throws SecurityException2352* In the case of the default provider, and a security manager is2353* installed, its {@link SecurityManager#checkRead(String) checkRead}2354* method denies read access to the file.2355*/2356public static boolean isRegularFile(Path path, LinkOption... options) {2357if (options.length == 0) {2358FileSystemProvider provider = provider(path);2359if (provider instanceof AbstractFileSystemProvider)2360return ((AbstractFileSystemProvider)provider).isRegularFile(path);2361}23622363try {2364return readAttributes(path, BasicFileAttributes.class, options).isRegularFile();2365} catch (IOException ioe) {2366return false;2367}2368}23692370/**2371* Returns a file's last modified time.2372*2373* <p> The {@code options} array may be used to indicate how symbolic links2374* are handled for the case that the file is a symbolic link. By default,2375* symbolic links are followed and the file attribute of the final target2376* of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS2377* NOFOLLOW_LINKS} is present then symbolic links are not followed.2378*2379* @param path2380* the path to the file2381* @param options2382* options indicating how symbolic links are handled2383*2384* @return a {@code FileTime} representing the time the file was last2385* modified, or an implementation specific default when a time2386* stamp to indicate the time of last modification is not supported2387* by the file system2388*2389* @throws IOException2390* if an I/O error occurs2391* @throws SecurityException2392* In the case of the default provider, and a security manager is2393* installed, its {@link SecurityManager#checkRead(String) checkRead}2394* method denies read access to the file.2395*2396* @see BasicFileAttributes#lastModifiedTime2397*/2398public static FileTime getLastModifiedTime(Path path, LinkOption... options)2399throws IOException2400{2401return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime();2402}24032404/**2405* Updates a file's last modified time attribute. The file time is converted2406* to the epoch and precision supported by the file system. Converting from2407* finer to coarser granularities result in precision loss. The behavior of2408* this method when attempting to set the last modified time when it is not2409* supported by the file system or is outside the range supported by the2410* underlying file store is not defined. It may or not fail by throwing an2411* {@code IOException}.2412*2413* <p> <b>Usage Example:</b>2414* Suppose we want to set the last modified time to the current time:2415* <pre>2416* Path path = ...2417* FileTime now = FileTime.fromMillis(System.currentTimeMillis());2418* Files.setLastModifiedTime(path, now);2419* </pre>2420*2421* @param path2422* the path to the file2423* @param time2424* the new last modified time2425*2426* @return the given path2427*2428* @throws IOException2429* if an I/O error occurs2430* @throws SecurityException2431* In the case of the default provider, and a security manager is2432* installed, its {@link SecurityManager#checkWrite(String)2433* checkWrite} method denies write access to the file.2434*2435* @see BasicFileAttributeView#setTimes2436*/2437public static Path setLastModifiedTime(Path path, FileTime time)2438throws IOException2439{2440getFileAttributeView(path, BasicFileAttributeView.class)2441.setTimes(Objects.requireNonNull(time), null, null);2442return path;2443}24442445/**2446* Returns the size of a file (in bytes). The size may differ from the2447* actual size on the file system due to compression, support for sparse2448* files, or other reasons. The size of files that are not {@link2449* #isRegularFile regular} files is implementation specific and2450* therefore unspecified.2451*2452* @param path2453* the path to the file2454*2455* @return the file size, in bytes2456*2457* @throws IOException2458* if an I/O error occurs2459* @throws SecurityException2460* In the case of the default provider, and a security manager is2461* installed, its {@link SecurityManager#checkRead(String) checkRead}2462* method denies read access to the file.2463*2464* @see BasicFileAttributes#size2465*/2466public static long size(Path path) throws IOException {2467return readAttributes(path, BasicFileAttributes.class).size();2468}24692470// -- Accessibility --24712472/**2473* Returns {@code false} if NOFOLLOW_LINKS is present.2474*/2475private static boolean followLinks(LinkOption... options) {2476boolean followLinks = true;2477for (LinkOption opt: options) {2478if (opt == LinkOption.NOFOLLOW_LINKS) {2479followLinks = false;2480continue;2481}2482if (opt == null)2483throw new NullPointerException();2484throw new AssertionError("Should not get here");2485}2486return followLinks;2487}24882489/**2490* Tests whether a file exists.2491*2492* <p> The {@code options} parameter may be used to indicate how symbolic links2493* are handled for the case that the file is a symbolic link. By default,2494* symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS2495* NOFOLLOW_LINKS} is present then symbolic links are not followed.2496*2497* <p> Note that the result of this method is immediately outdated. If this2498* method indicates the file exists then there is no guarantee that a2499* subsequent access will succeed. Care should be taken when using this2500* method in security sensitive applications.2501*2502* @param path2503* the path to the file to test2504* @param options2505* options indicating how symbolic links are handled2506* .2507* @return {@code true} if the file exists; {@code false} if the file does2508* not exist or its existence cannot be determined.2509*2510* @throws SecurityException2511* In the case of the default provider, the {@link2512* SecurityManager#checkRead(String)} is invoked to check2513* read access to the file.2514*2515* @see #notExists2516*/2517public static boolean exists(Path path, LinkOption... options) {2518if (options.length == 0) {2519FileSystemProvider provider = provider(path);2520if (provider instanceof AbstractFileSystemProvider)2521return ((AbstractFileSystemProvider)provider).exists(path);2522}25232524try {2525if (followLinks(options)) {2526provider(path).checkAccess(path);2527} else {2528// attempt to read attributes without following links2529readAttributes(path, BasicFileAttributes.class,2530LinkOption.NOFOLLOW_LINKS);2531}2532// file exists2533return true;2534} catch (IOException x) {2535// does not exist or unable to determine if file exists2536return false;2537}25382539}25402541/**2542* Tests whether the file located by this path does not exist. This method2543* is intended for cases where it is required to take action when it can be2544* confirmed that a file does not exist.2545*2546* <p> The {@code options} parameter may be used to indicate how symbolic links2547* are handled for the case that the file is a symbolic link. By default,2548* symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS2549* NOFOLLOW_LINKS} is present then symbolic links are not followed.2550*2551* <p> Note that this method is not the complement of the {@link #exists2552* exists} method. Where it is not possible to determine if a file exists2553* or not then both methods return {@code false}. As with the {@code exists}2554* method, the result of this method is immediately outdated. If this2555* method indicates the file does exist then there is no guarantee that a2556* subsequent attempt to create the file will succeed. Care should be taken2557* when using this method in security sensitive applications.2558*2559* @param path2560* the path to the file to test2561* @param options2562* options indicating how symbolic links are handled2563*2564* @return {@code true} if the file does not exist; {@code false} if the2565* file exists or its existence cannot be determined2566*2567* @throws SecurityException2568* In the case of the default provider, the {@link2569* SecurityManager#checkRead(String)} is invoked to check2570* read access to the file.2571*/2572public static boolean notExists(Path path, LinkOption... options) {2573try {2574if (followLinks(options)) {2575provider(path).checkAccess(path);2576} else {2577// attempt to read attributes without following links2578readAttributes(path, BasicFileAttributes.class,2579LinkOption.NOFOLLOW_LINKS);2580}2581// file exists2582return false;2583} catch (NoSuchFileException x) {2584// file confirmed not to exist2585return true;2586} catch (IOException x) {2587return false;2588}2589}25902591/**2592* Used by isReadable, isWritable, isExecutable to test access to a file.2593*/2594private static boolean isAccessible(Path path, AccessMode... modes) {2595try {2596provider(path).checkAccess(path, modes);2597return true;2598} catch (IOException x) {2599return false;2600}2601}26022603/**2604* Tests whether a file is readable. This method checks that a file exists2605* and that this Java virtual machine has appropriate privileges that would2606* allow it open the file for reading. Depending on the implementation, this2607* method may require to read file permissions, access control lists, or2608* other file attributes in order to check the effective access to the file.2609* Consequently, this method may not be atomic with respect to other file2610* system operations.2611*2612* <p> Note that the result of this method is immediately outdated, there is2613* no guarantee that a subsequent attempt to open the file for reading will2614* succeed (or even that it will access the same file). Care should be taken2615* when using this method in security sensitive applications.2616*2617* @param path2618* the path to the file to check2619*2620* @return {@code true} if the file exists and is readable; {@code false}2621* if the file does not exist, read access would be denied because2622* the Java virtual machine has insufficient privileges, or access2623* cannot be determined2624*2625* @throws SecurityException2626* In the case of the default provider, and a security manager is2627* installed, the {@link SecurityManager#checkRead(String) checkRead}2628* is invoked to check read access to the file.2629*/2630public static boolean isReadable(Path path) {2631return isAccessible(path, AccessMode.READ);2632}26332634/**2635* Tests whether a file is writable. This method checks that a file exists2636* and that this Java virtual machine has appropriate privileges that would2637* allow it open the file for writing. Depending on the implementation, this2638* method may require to read file permissions, access control lists, or2639* other file attributes in order to check the effective access to the file.2640* Consequently, this method may not be atomic with respect to other file2641* system operations.2642*2643* <p> Note that result of this method is immediately outdated, there is no2644* guarantee that a subsequent attempt to open the file for writing will2645* succeed (or even that it will access the same file). Care should be taken2646* when using this method in security sensitive applications.2647*2648* @param path2649* the path to the file to check2650*2651* @return {@code true} if the file exists and is writable; {@code false}2652* if the file does not exist, write access would be denied because2653* the Java virtual machine has insufficient privileges, or access2654* cannot be determined2655*2656* @throws SecurityException2657* In the case of the default provider, and a security manager is2658* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2659* is invoked to check write access to the file.2660*/2661public static boolean isWritable(Path path) {2662return isAccessible(path, AccessMode.WRITE);2663}26642665/**2666* Tests whether a file is executable. This method checks that a file exists2667* and that this Java virtual machine has appropriate privileges to {@link2668* Runtime#exec execute} the file. The semantics may differ when checking2669* access to a directory. For example, on UNIX systems, checking for2670* execute access checks that the Java virtual machine has permission to2671* search the directory in order to access file or subdirectories.2672*2673* <p> Depending on the implementation, this method may require to read file2674* permissions, access control lists, or other file attributes in order to2675* check the effective access to the file. Consequently, this method may not2676* be atomic with respect to other file system operations.2677*2678* <p> Note that the result of this method is immediately outdated, there is2679* no guarantee that a subsequent attempt to execute the file will succeed2680* (or even that it will access the same file). Care should be taken when2681* using this method in security sensitive applications.2682*2683* @param path2684* the path to the file to check2685*2686* @return {@code true} if the file exists and is executable; {@code false}2687* if the file does not exist, execute access would be denied because2688* the Java virtual machine has insufficient privileges, or access2689* cannot be determined2690*2691* @throws SecurityException2692* In the case of the default provider, and a security manager is2693* installed, the {@link SecurityManager#checkExec(String)2694* checkExec} is invoked to check execute access to the file.2695*/2696public static boolean isExecutable(Path path) {2697return isAccessible(path, AccessMode.EXECUTE);2698}26992700// -- Recursive operations --27012702/**2703* Walks a file tree.2704*2705* <p> This method walks a file tree rooted at a given starting file. The2706* file tree traversal is <em>depth-first</em> with the given {@link2707* FileVisitor} invoked for each file encountered. File tree traversal2708* completes when all accessible files in the tree have been visited, or a2709* visit method returns a result of {@link FileVisitResult#TERMINATE2710* TERMINATE}. Where a visit method terminates due an {@code IOException},2711* an uncaught error, or runtime exception, then the traversal is terminated2712* and the error or exception is propagated to the caller of this method.2713*2714* <p> For each file encountered this method attempts to read its {@link2715* java.nio.file.attribute.BasicFileAttributes}. If the file is not a2716* directory then the {@link FileVisitor#visitFile visitFile} method is2717* invoked with the file attributes. If the file attributes cannot be read,2718* due to an I/O exception, then the {@link FileVisitor#visitFileFailed2719* visitFileFailed} method is invoked with the I/O exception.2720*2721* <p> Where the file is a directory, and the directory could not be opened,2722* then the {@code visitFileFailed} method is invoked with the I/O exception,2723* after which, the file tree walk continues, by default, at the next2724* <em>sibling</em> of the directory.2725*2726* <p> Where the directory is opened successfully, then the entries in the2727* directory, and their <em>descendants</em> are visited. When all entries2728* have been visited, or an I/O error occurs during iteration of the2729* directory, then the directory is closed and the visitor's {@link2730* FileVisitor#postVisitDirectory postVisitDirectory} method is invoked.2731* The file tree walk then continues, by default, at the next <em>sibling</em>2732* of the directory.2733*2734* <p> By default, symbolic links are not automatically followed by this2735* method. If the {@code options} parameter contains the {@link2736* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are2737* followed. When following links, and the attributes of the target cannot2738* be read, then this method attempts to get the {@code BasicFileAttributes}2739* of the link. If they can be read then the {@code visitFile} method is2740* invoked with the attributes of the link (otherwise the {@code visitFileFailed}2741* method is invoked as specified above).2742*2743* <p> If the {@code options} parameter contains the {@link2744* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps2745* track of directories visited so that cycles can be detected. A cycle2746* arises when there is an entry in a directory that is an ancestor of the2747* directory. Cycle detection is done by recording the {@link2748* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,2749* or if file keys are not available, by invoking the {@link #isSameFile2750* isSameFile} method to test if a directory is the same file as an2751* ancestor. When a cycle is detected it is treated as an I/O error, and the2752* {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with2753* an instance of {@link FileSystemLoopException}.2754*2755* <p> The {@code maxDepth} parameter is the maximum number of levels of2756* directories to visit. A value of {@code 0} means that only the starting2757* file is visited, unless denied by the security manager. A value of2758* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all2759* levels should be visited. The {@code visitFile} method is invoked for all2760* files, including directories, encountered at {@code maxDepth}, unless the2761* basic file attributes cannot be read, in which case the {@code2762* visitFileFailed} method is invoked.2763*2764* <p> If a visitor returns a result of {@code null} then {@code2765* NullPointerException} is thrown.2766*2767* <p> When a security manager is installed and it denies access to a file2768* (or directory), then it is ignored and the visitor is not invoked for2769* that file (or directory).2770*2771* @param start2772* the starting file2773* @param options2774* options to configure the traversal2775* @param maxDepth2776* the maximum number of directory levels to visit2777* @param visitor2778* the file visitor to invoke for each file2779*2780* @return the starting file2781*2782* @throws IllegalArgumentException2783* if the {@code maxDepth} parameter is negative2784* @throws SecurityException2785* If the security manager denies access to the starting file.2786* In the case of the default provider, the {@link2787* SecurityManager#checkRead(String) checkRead} method is invoked2788* to check read access to the directory.2789* @throws IOException2790* if an I/O error is thrown by a visitor method2791*/2792public static Path walkFileTree(Path start,2793Set<FileVisitOption> options,2794int maxDepth,2795FileVisitor<? super Path> visitor)2796throws IOException2797{2798/**2799* Create a FileTreeWalker to walk the file tree, invoking the visitor2800* for each event.2801*/2802try (FileTreeWalker walker = new FileTreeWalker(options, maxDepth)) {2803FileTreeWalker.Event ev = walker.walk(start);2804do {2805FileVisitResult result;2806switch (ev.type()) {2807case ENTRY :2808IOException ioe = ev.ioeException();2809if (ioe == null) {2810assert ev.attributes() != null;2811result = visitor.visitFile(ev.file(), ev.attributes());2812} else {2813result = visitor.visitFileFailed(ev.file(), ioe);2814}2815break;28162817case START_DIRECTORY :2818result = visitor.preVisitDirectory(ev.file(), ev.attributes());28192820// if SKIP_SIBLINGS and SKIP_SUBTREE is returned then2821// there shouldn't be any more events for the current2822// directory.2823if (result == FileVisitResult.SKIP_SUBTREE ||2824result == FileVisitResult.SKIP_SIBLINGS)2825walker.pop();2826break;28272828case END_DIRECTORY :2829result = visitor.postVisitDirectory(ev.file(), ev.ioeException());28302831// SKIP_SIBLINGS is a no-op for postVisitDirectory2832if (result == FileVisitResult.SKIP_SIBLINGS)2833result = FileVisitResult.CONTINUE;2834break;28352836default :2837throw new AssertionError("Should not get here");2838}28392840if (Objects.requireNonNull(result) != FileVisitResult.CONTINUE) {2841if (result == FileVisitResult.TERMINATE) {2842break;2843} else if (result == FileVisitResult.SKIP_SIBLINGS) {2844walker.skipRemainingSiblings();2845}2846}2847ev = walker.next();2848} while (ev != null);2849}28502851return start;2852}28532854/**2855* Walks a file tree.2856*2857* <p> This method works as if invoking it were equivalent to evaluating the2858* expression:2859* <blockquote>{@link2860* walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor<? super Path>)2861* Files.walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)2862* }</blockquote>2863* In other words, it does not follow symbolic links, and visits all levels2864* of the file tree.2865*2866* @param start2867* the starting file2868* @param visitor2869* the file visitor to invoke for each file2870*2871* @return the starting file2872*2873* @throws SecurityException2874* If the security manager denies access to the starting file.2875* In the case of the default provider, the {@link2876* SecurityManager#checkRead(String) checkRead} method is invoked2877* to check read access to the directory.2878* @throws IOException2879* if an I/O error is thrown by a visitor method2880*/2881public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)2882throws IOException2883{2884return walkFileTree(start,2885EnumSet.noneOf(FileVisitOption.class),2886Integer.MAX_VALUE,2887visitor);2888}288928902891// -- Utility methods for simple usages --289228932894/**2895* Opens a file for reading, returning a {@code BufferedReader} that may be2896* used to read text from the file in an efficient manner. Bytes from the2897* file are decoded into characters using the specified charset. Reading2898* commences at the beginning of the file.2899*2900* <p> The {@code Reader} methods that read from the file throw {@code2901* IOException} if a malformed or unmappable byte sequence is read.2902*2903* @param path2904* the path to the file2905* @param cs2906* the charset to use for decoding2907*2908* @return a new buffered reader, with default buffer size, to read text2909* from the file2910*2911* @throws IOException2912* if an I/O error occurs opening the file2913* @throws SecurityException2914* In the case of the default provider, and a security manager is2915* installed, the {@link SecurityManager#checkRead(String) checkRead}2916* method is invoked to check read access to the file.2917*2918* @see #readAllLines2919*/2920public static BufferedReader newBufferedReader(Path path, Charset cs)2921throws IOException2922{2923CharsetDecoder decoder = cs.newDecoder();2924Reader reader = new InputStreamReader(newInputStream(path), decoder);2925return new BufferedReader(reader);2926}29272928/**2929* Opens a file for reading, returning a {@code BufferedReader} to read text2930* from the file in an efficient manner. Bytes from the file are decoded into2931* characters using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset2932* charset}.2933*2934* <p> This method works as if invoking it were equivalent to evaluating the2935* expression:2936* <blockquote>{@link2937* newBufferedReader(Path, Charset)2938* Files.newBufferedReader(path, StandardCharsets.UTF_8)2939* }</blockquote>2940*2941* @param path2942* the path to the file2943*2944* @return a new buffered reader, with default buffer size, to read text2945* from the file2946*2947* @throws IOException2948* if an I/O error occurs opening the file2949* @throws SecurityException2950* In the case of the default provider, and a security manager is2951* installed, the {@link SecurityManager#checkRead(String) checkRead}2952* method is invoked to check read access to the file.2953*2954* @since 1.82955*/2956public static BufferedReader newBufferedReader(Path path) throws IOException {2957return newBufferedReader(path, UTF_8.INSTANCE);2958}29592960/**2961* Opens or creates a file for writing, returning a {@code BufferedWriter}2962* that may be used to write text to the file in an efficient manner.2963* The {@code options} parameter specifies how the file is created or2964* opened. If no options are present then this method works as if the {@link2965* StandardOpenOption#CREATE CREATE}, {@link2966* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link2967* StandardOpenOption#WRITE WRITE} options are present. In other words, it2968* opens the file for writing, creating the file if it doesn't exist, or2969* initially truncating an existing {@link #isRegularFile regular-file} to2970* a size of {@code 0} if it exists.2971*2972* <p> The {@code Writer} methods to write text throw {@code IOException}2973* if the text cannot be encoded using the specified charset.2974*2975* @param path2976* the path to the file2977* @param cs2978* the charset to use for encoding2979* @param options2980* options specifying how the file is opened2981*2982* @return a new buffered writer, with default buffer size, to write text2983* to the file2984*2985* @throws IllegalArgumentException2986* if {@code options} contains an invalid combination of options2987* @throws IOException2988* if an I/O error occurs opening or creating the file2989* @throws UnsupportedOperationException2990* if an unsupported option is specified2991* @throws FileAlreadyExistsException2992* If a file of that name already exists and the {@link2993* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified2994* <i>(optional specific exception)</i>2995* @throws SecurityException2996* In the case of the default provider, and a security manager is2997* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2998* method is invoked to check write access to the file. The {@link2999* SecurityManager#checkDelete(String) checkDelete} method is3000* invoked to check delete access if the file is opened with the3001* {@code DELETE_ON_CLOSE} option.3002*3003* @see #write(Path,Iterable,Charset,OpenOption[])3004*/3005public static BufferedWriter newBufferedWriter(Path path, Charset cs,3006OpenOption... options)3007throws IOException3008{3009CharsetEncoder encoder = cs.newEncoder();3010Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder);3011return new BufferedWriter(writer);3012}30133014/**3015* Opens or creates a file for writing, returning a {@code BufferedWriter}3016* to write text to the file in an efficient manner. The text is encoded3017* into bytes for writing using the {@link StandardCharsets#UTF_8 UTF-8}3018* {@link Charset charset}.3019*3020* <p> This method works as if invoking it were equivalent to evaluating the3021* expression:3022* <blockquote>{@link3023* newBufferedWriter(Path, Charset, OpenOption...)3024* Files.newBufferedWriter(path, StandardCharsets.UTF_8, options)3025* }</blockquote>3026*3027* @param path3028* the path to the file3029* @param options3030* options specifying how the file is opened3031*3032* @return a new buffered writer, with default buffer size, to write text3033* to the file3034*3035* @throws IllegalArgumentException3036* if {@code options} contains an invalid combination of options3037* @throws IOException3038* if an I/O error occurs opening or creating the file3039* @throws UnsupportedOperationException3040* if an unsupported option is specified3041* @throws FileAlreadyExistsException3042* If a file of that name already exists and the {@link3043* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3044* <i>(optional specific exception)</i>3045* @throws SecurityException3046* In the case of the default provider, and a security manager is3047* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3048* method is invoked to check write access to the file. The {@link3049* SecurityManager#checkDelete(String) checkDelete} method is3050* invoked to check delete access if the file is opened with the3051* {@code DELETE_ON_CLOSE} option.3052*3053* @since 1.83054*/3055public static BufferedWriter newBufferedWriter(Path path, OpenOption... options)3056throws IOException3057{3058return newBufferedWriter(path, UTF_8.INSTANCE, options);3059}30603061/**3062* Copies all bytes from an input stream to a file. On return, the input3063* stream will be at end of stream.3064*3065* <p> By default, the copy fails if the target file already exists or is a3066* symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING3067* REPLACE_EXISTING} option is specified, and the target file already exists,3068* then it is replaced if it is not a non-empty directory. If the target3069* file exists and is a symbolic link, then the symbolic link is replaced.3070* In this release, the {@code REPLACE_EXISTING} option is the only option3071* required to be supported by this method. Additional options may be3072* supported in future releases.3073*3074* <p> If an I/O error occurs reading from the input stream or writing to3075* the file, then it may do so after the target file has been created and3076* after some bytes have been read or written. Consequently the input3077* stream may not be at end of stream and may be in an inconsistent state.3078* It is strongly recommended that the input stream be promptly closed if an3079* I/O error occurs.3080*3081* <p> This method may block indefinitely reading from the input stream (or3082* writing to the file). The behavior for the case that the input stream is3083* <i>asynchronously closed</i> or the thread interrupted during the copy is3084* highly input stream and file system provider specific and therefore not3085* specified.3086*3087* <p> <b>Usage example</b>: Suppose we want to capture a web page and save3088* it to a file:3089* <pre>3090* Path path = ...3091* URI u = URI.create("http://www.example.com/");3092* try (InputStream in = u.toURL().openStream()) {3093* Files.copy(in, path);3094* }3095* </pre>3096*3097* @param in3098* the input stream to read from3099* @param target3100* the path to the file3101* @param options3102* options specifying how the copy should be done3103*3104* @return the number of bytes read or written3105*3106* @throws IOException3107* if an I/O error occurs when reading or writing3108* @throws FileAlreadyExistsException3109* if the target file exists but cannot be replaced because the3110* {@code REPLACE_EXISTING} option is not specified <i>(optional3111* specific exception)</i>3112* @throws DirectoryNotEmptyException3113* the {@code REPLACE_EXISTING} option is specified but the file3114* cannot be replaced because it is a non-empty directory3115* <i>(optional specific exception)</i> *3116* @throws UnsupportedOperationException3117* if {@code options} contains a copy option that is not supported3118* @throws SecurityException3119* In the case of the default provider, and a security manager is3120* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3121* method is invoked to check write access to the file. Where the3122* {@code REPLACE_EXISTING} option is specified, the security3123* manager's {@link SecurityManager#checkDelete(String) checkDelete}3124* method is invoked to check that an existing file can be deleted.3125*/3126public static long copy(InputStream in, Path target, CopyOption... options)3127throws IOException3128{3129// ensure not null before opening file3130Objects.requireNonNull(in);31313132// check for REPLACE_EXISTING3133boolean replaceExisting = false;3134for (CopyOption opt: options) {3135if (opt == StandardCopyOption.REPLACE_EXISTING) {3136replaceExisting = true;3137} else {3138if (opt == null) {3139throw new NullPointerException("options contains 'null'");3140} else {3141throw new UnsupportedOperationException(opt + " not supported");3142}3143}3144}31453146// attempt to delete an existing file3147SecurityException se = null;3148if (replaceExisting) {3149try {3150deleteIfExists(target);3151} catch (SecurityException x) {3152se = x;3153}3154}31553156// attempt to create target file. If it fails with3157// FileAlreadyExistsException then it may be because the security3158// manager prevented us from deleting the file, in which case we just3159// throw the SecurityException.3160OutputStream ostream;3161try {3162ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,3163StandardOpenOption.WRITE);3164} catch (FileAlreadyExistsException x) {3165if (se != null)3166throw se;3167// someone else won the race and created the file3168throw x;3169}31703171// do the copy3172try (OutputStream out = ostream) {3173return in.transferTo(out);3174}3175}31763177/**3178* Copies all bytes from a file to an output stream.3179*3180* <p> If an I/O error occurs reading from the file or writing to the output3181* stream, then it may do so after some bytes have been read or written.3182* Consequently the output stream may be in an inconsistent state. It is3183* strongly recommended that the output stream be promptly closed if an I/O3184* error occurs.3185*3186* <p> This method may block indefinitely writing to the output stream (or3187* reading from the file). The behavior for the case that the output stream3188* is <i>asynchronously closed</i> or the thread interrupted during the copy3189* is highly output stream and file system provider specific and therefore3190* not specified.3191*3192* <p> Note that if the given output stream is {@link java.io.Flushable}3193* then its {@link java.io.Flushable#flush flush} method may need to invoked3194* after this method completes so as to flush any buffered output.3195*3196* @param source3197* the path to the file3198* @param out3199* the output stream to write to3200*3201* @return the number of bytes read or written3202*3203* @throws IOException3204* if an I/O error occurs when reading or writing3205* @throws SecurityException3206* In the case of the default provider, and a security manager is3207* installed, the {@link SecurityManager#checkRead(String) checkRead}3208* method is invoked to check read access to the file.3209*/3210public static long copy(Path source, OutputStream out) throws IOException {3211// ensure not null before opening file3212Objects.requireNonNull(out);32133214try (InputStream in = newInputStream(source)) {3215return in.transferTo(out);3216}3217}32183219private static final jdk.internal.access.JavaLangAccess JLA =3220jdk.internal.access.SharedSecrets.getJavaLangAccess();32213222/**3223* Reads all the bytes from an input stream. Uses {@code initialSize} as a hint3224* about how many bytes the stream will have.3225*3226* @param source3227* the input stream to read from3228* @param initialSize3229* the initial size of the byte array to allocate3230*3231* @return a byte array containing the bytes read from the file3232*3233* @throws IOException3234* if an I/O error occurs reading from the stream3235* @throws OutOfMemoryError3236* if an array of the required size cannot be allocated3237*/3238private static byte[] read(InputStream source, int initialSize) throws IOException {3239int capacity = initialSize;3240byte[] buf = new byte[capacity];3241int nread = 0;3242int n;3243for (;;) {3244// read to EOF which may read more or less than initialSize (eg: file3245// is truncated while we are reading)3246while ((n = source.read(buf, nread, capacity - nread)) > 0)3247nread += n;32483249// if last call to source.read() returned -1, we are done3250// otherwise, try to read one more byte; if that failed we're done too3251if (n < 0 || (n = source.read()) < 0)3252break;32533254// one more byte was read; need to allocate a larger buffer3255capacity = Math.max(ArraysSupport.newLength(capacity,32561, /* minimum growth */3257capacity /* preferred growth */),3258BUFFER_SIZE);3259buf = Arrays.copyOf(buf, capacity);3260buf[nread++] = (byte)n;3261}3262return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);3263}32643265/**3266* Reads all the bytes from a file. The method ensures that the file is3267* closed when all bytes have been read or an I/O error, or other runtime3268* exception, is thrown.3269*3270* <p> Note that this method is intended for simple cases where it is3271* convenient to read all bytes into a byte array. It is not intended for3272* reading in large files.3273*3274* @param path3275* the path to the file3276*3277* @return a byte array containing the bytes read from the file3278*3279* @throws IOException3280* if an I/O error occurs reading from the stream3281* @throws OutOfMemoryError3282* if an array of the required size cannot be allocated, for3283* example the file is larger that {@code 2GB}3284* @throws SecurityException3285* In the case of the default provider, and a security manager is3286* installed, the {@link SecurityManager#checkRead(String) checkRead}3287* method is invoked to check read access to the file.3288*/3289public static byte[] readAllBytes(Path path) throws IOException {3290try (SeekableByteChannel sbc = Files.newByteChannel(path);3291InputStream in = Channels.newInputStream(sbc)) {3292if (sbc instanceof FileChannelImpl)3293((FileChannelImpl) sbc).setUninterruptible();3294long size = sbc.size();3295if (size > (long) Integer.MAX_VALUE)3296throw new OutOfMemoryError("Required array size too large");3297return read(in, (int)size);3298}3299}33003301/**3302* Reads all content from a file into a string, decoding from bytes to characters3303* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3304* The method ensures that the file is closed when all content have been read3305* or an I/O error, or other runtime exception, is thrown.3306*3307* <p> This method is equivalent to: {@link readString(Path, Charset)3308* readString(path, StandardCharsets.UTF_8)}.3309*3310* @param path the path to the file3311*3312* @return a String containing the content read from the file3313*3314* @throws IOException3315* if an I/O error occurs reading from the file or a malformed or3316* unmappable byte sequence is read3317* @throws OutOfMemoryError3318* if the file is extremely large, for example larger than {@code 2GB}3319* @throws SecurityException3320* In the case of the default provider, and a security manager is3321* installed, the {@link SecurityManager#checkRead(String) checkRead}3322* method is invoked to check read access to the file.3323*3324* @since 113325*/3326public static String readString(Path path) throws IOException {3327return readString(path, UTF_8.INSTANCE);3328}33293330/**3331* Reads all characters from a file into a string, decoding from bytes to characters3332* using the specified {@linkplain Charset charset}.3333* The method ensures that the file is closed when all content have been read3334* or an I/O error, or other runtime exception, is thrown.3335*3336* <p> This method reads all content including the line separators in the middle3337* and/or at the end. The resulting string will contain line separators as they3338* appear in the file.3339*3340* @apiNote3341* This method is intended for simple cases where it is appropriate and convenient3342* to read the content of a file into a String. It is not intended for reading3343* very large files.3344*3345*3346*3347* @param path the path to the file3348* @param cs the charset to use for decoding3349*3350* @return a String containing the content read from the file3351*3352* @throws IOException3353* if an I/O error occurs reading from the file or a malformed or3354* unmappable byte sequence is read3355* @throws OutOfMemoryError3356* if the file is extremely large, for example larger than {@code 2GB}3357* @throws SecurityException3358* In the case of the default provider, and a security manager is3359* installed, the {@link SecurityManager#checkRead(String) checkRead}3360* method is invoked to check read access to the file.3361*3362* @since 113363*/3364public static String readString(Path path, Charset cs) throws IOException {3365Objects.requireNonNull(path);3366Objects.requireNonNull(cs);33673368byte[] ba = readAllBytes(path);3369if (path.getClass().getModule() != Object.class.getModule())3370ba = ba.clone();3371return JLA.newStringNoRepl(ba, cs);3372}33733374/**3375* Read all lines from a file. This method ensures that the file is3376* closed when all bytes have been read or an I/O error, or other runtime3377* exception, is thrown. Bytes from the file are decoded into characters3378* using the specified charset.3379*3380* <p> This method recognizes the following as line terminators:3381* <ul>3382* <li> <code>\u000D</code> followed by <code>\u000A</code>,3383* CARRIAGE RETURN followed by LINE FEED </li>3384* <li> <code>\u000A</code>, LINE FEED </li>3385* <li> <code>\u000D</code>, CARRIAGE RETURN </li>3386* </ul>3387* <p> Additional Unicode line terminators may be recognized in future3388* releases.3389*3390* <p> Note that this method is intended for simple cases where it is3391* convenient to read all lines in a single operation. It is not intended3392* for reading in large files.3393*3394* @param path3395* the path to the file3396* @param cs3397* the charset to use for decoding3398*3399* @return the lines from the file as a {@code List}; whether the {@code3400* List} is modifiable or not is implementation dependent and3401* therefore not specified3402*3403* @throws IOException3404* if an I/O error occurs reading from the file or a malformed or3405* unmappable byte sequence is read3406* @throws SecurityException3407* In the case of the default provider, and a security manager is3408* installed, the {@link SecurityManager#checkRead(String) checkRead}3409* method is invoked to check read access to the file.3410*3411* @see #newBufferedReader3412*/3413public static List<String> readAllLines(Path path, Charset cs) throws IOException {3414try (BufferedReader reader = newBufferedReader(path, cs)) {3415List<String> result = new ArrayList<>();3416for (;;) {3417String line = reader.readLine();3418if (line == null)3419break;3420result.add(line);3421}3422return result;3423}3424}34253426/**3427* Read all lines from a file. Bytes from the file are decoded into characters3428* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3429*3430* <p> This method works as if invoking it were equivalent to evaluating the3431* expression:3432* <blockquote>{@link3433* readAllLines(Path, Charset)3434* Files.readAllLines(path, StandardCharsets.UTF_8)3435* }</blockquote>3436*3437* @param path3438* the path to the file3439*3440* @return the lines from the file as a {@code List}; whether the {@code3441* List} is modifiable or not is implementation dependent and3442* therefore not specified3443*3444* @throws IOException3445* if an I/O error occurs reading from the file or a malformed or3446* unmappable byte sequence is read3447* @throws SecurityException3448* In the case of the default provider, and a security manager is3449* installed, the {@link SecurityManager#checkRead(String) checkRead}3450* method is invoked to check read access to the file.3451*3452* @since 1.83453*/3454public static List<String> readAllLines(Path path) throws IOException {3455return readAllLines(path, UTF_8.INSTANCE);3456}34573458/**3459* Writes bytes to a file. The {@code options} parameter specifies how3460* the file is created or opened. If no options are present then this method3461* works as if the {@link StandardOpenOption#CREATE CREATE}, {@link3462* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3463* StandardOpenOption#WRITE WRITE} options are present. In other words, it3464* opens the file for writing, creating the file if it doesn't exist, or3465* initially truncating an existing {@link #isRegularFile regular-file} to3466* a size of {@code 0}. All bytes in the byte array are written to the file.3467* The method ensures that the file is closed when all bytes have been3468* written (or an I/O error or other runtime exception is thrown). If an I/O3469* error occurs then it may do so after the file has been created or3470* truncated, or after some bytes have been written to the file.3471*3472* <p> <b>Usage example</b>: By default the method creates a new file or3473* overwrites an existing file. Suppose you instead want to append bytes3474* to an existing file:3475* <pre>3476* Path path = ...3477* byte[] bytes = ...3478* Files.write(path, bytes, StandardOpenOption.APPEND);3479* </pre>3480*3481* @param path3482* the path to the file3483* @param bytes3484* the byte array with the bytes to write3485* @param options3486* options specifying how the file is opened3487*3488* @return the path3489*3490* @throws IllegalArgumentException3491* if {@code options} contains an invalid combination of options3492* @throws IOException3493* if an I/O error occurs writing to or creating the file3494* @throws UnsupportedOperationException3495* if an unsupported option is specified3496* @throws FileAlreadyExistsException3497* If a file of that name already exists and the {@link3498* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3499* <i>(optional specific exception)</i>3500* @throws SecurityException3501* In the case of the default provider, and a security manager is3502* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3503* method is invoked to check write access to the file. The {@link3504* SecurityManager#checkDelete(String) checkDelete} method is3505* invoked to check delete access if the file is opened with the3506* {@code DELETE_ON_CLOSE} option.3507*/3508public static Path write(Path path, byte[] bytes, OpenOption... options)3509throws IOException3510{3511// ensure bytes is not null before opening file3512Objects.requireNonNull(bytes);35133514try (OutputStream out = Files.newOutputStream(path, options)) {3515int len = bytes.length;3516int rem = len;3517while (rem > 0) {3518int n = Math.min(rem, BUFFER_SIZE);3519out.write(bytes, (len-rem), n);3520rem -= n;3521}3522}3523return path;3524}35253526/**3527* Write lines of text to a file. Each line is a char sequence and is3528* written to the file in sequence with each line terminated by the3529* platform's line separator, as defined by the system property {@code3530* line.separator}. Characters are encoded into bytes using the specified3531* charset.3532*3533* <p> The {@code options} parameter specifies how the file is created3534* or opened. If no options are present then this method works as if the3535* {@link StandardOpenOption#CREATE CREATE}, {@link3536* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3537* StandardOpenOption#WRITE WRITE} options are present. In other words, it3538* opens the file for writing, creating the file if it doesn't exist, or3539* initially truncating an existing {@link #isRegularFile regular-file} to3540* a size of {@code 0}. The method ensures that the file is closed when all3541* lines have been written (or an I/O error or other runtime exception is3542* thrown). If an I/O error occurs then it may do so after the file has3543* been created or truncated, or after some bytes have been written to the3544* file.3545*3546* @param path3547* the path to the file3548* @param lines3549* an object to iterate over the char sequences3550* @param cs3551* the charset to use for encoding3552* @param options3553* options specifying how the file is opened3554*3555* @return the path3556*3557* @throws IllegalArgumentException3558* if {@code options} contains an invalid combination of options3559* @throws IOException3560* if an I/O error occurs writing to or creating the file, or the3561* text cannot be encoded using the specified charset3562* @throws UnsupportedOperationException3563* if an unsupported option is specified3564* @throws FileAlreadyExistsException3565* If a file of that name already exists and the {@link3566* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3567* <i>(optional specific exception)</i>3568* @throws SecurityException3569* In the case of the default provider, and a security manager is3570* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3571* method is invoked to check write access to the file. The {@link3572* SecurityManager#checkDelete(String) checkDelete} method is3573* invoked to check delete access if the file is opened with the3574* {@code DELETE_ON_CLOSE} option.3575*/3576public static Path write(Path path, Iterable<? extends CharSequence> lines,3577Charset cs, OpenOption... options)3578throws IOException3579{3580// ensure lines is not null before opening file3581Objects.requireNonNull(lines);3582CharsetEncoder encoder = cs.newEncoder();3583try (OutputStream out = newOutputStream(path, options);3584BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {3585for (CharSequence line: lines) {3586writer.append(line);3587writer.newLine();3588}3589}3590return path;3591}35923593/**3594* Write lines of text to a file. Characters are encoded into bytes using3595* the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3596*3597* <p> This method works as if invoking it were equivalent to evaluating the3598* expression:3599* <blockquote>{@link3600* write(Path, Iterable<? extends CharSequence>, Charset, OpenOption...)3601* Files.write(path, lines, StandardCharsets.UTF_8, options)3602* }</blockquote>3603*3604* @param path3605* the path to the file3606* @param lines3607* an object to iterate over the char sequences3608* @param options3609* options specifying how the file is opened3610*3611* @return the path3612*3613* @throws IllegalArgumentException3614* if {@code options} contains an invalid combination of options3615* @throws IOException3616* if an I/O error occurs writing to or creating the file, or the3617* text cannot be encoded as {@code UTF-8}3618* @throws UnsupportedOperationException3619* if an unsupported option is specified3620* @throws SecurityException3621* In the case of the default provider, and a security manager is3622* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3623* method is invoked to check write access to the file. The {@link3624* SecurityManager#checkDelete(String) checkDelete} method is3625* invoked to check delete access if the file is opened with the3626* {@code DELETE_ON_CLOSE} option.3627*3628* @since 1.83629*/3630public static Path write(Path path,3631Iterable<? extends CharSequence> lines,3632OpenOption... options)3633throws IOException3634{3635return write(path, lines, UTF_8.INSTANCE, options);3636}36373638/**3639* Write a {@linkplain java.lang.CharSequence CharSequence} to a file.3640* Characters are encoded into bytes using the3641* {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3642*3643* <p> This method is equivalent to: {@link3644* writeString(Path, CharSequence, Charset, OpenOption...)3645* writeString(path, csq, StandardCharsets.UTF_8, options)}.3646*3647* @param path3648* the path to the file3649* @param csq3650* the CharSequence to be written3651* @param options3652* options specifying how the file is opened3653*3654* @return the path3655*3656* @throws IllegalArgumentException3657* if {@code options} contains an invalid combination of options3658* @throws IOException3659* if an I/O error occurs writing to or creating the file, or the3660* text cannot be encoded using the specified charset3661* @throws UnsupportedOperationException3662* if an unsupported option is specified3663* @throws SecurityException3664* In the case of the default provider, and a security manager is3665* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3666* method is invoked to check write access to the file. The {@link3667* SecurityManager#checkDelete(String) checkDelete} method is3668* invoked to check delete access if the file is opened with the3669* {@code DELETE_ON_CLOSE} option.3670*3671* @since 113672*/3673public static Path writeString(Path path, CharSequence csq, OpenOption... options)3674throws IOException3675{3676return writeString(path, csq, UTF_8.INSTANCE, options);3677}36783679/**3680* Write a {@linkplain java.lang.CharSequence CharSequence} to a file.3681* Characters are encoded into bytes using the specified3682* {@linkplain java.nio.charset.Charset charset}.3683*3684* <p> All characters are written as they are, including the line separators in3685* the char sequence. No extra characters are added.3686*3687* <p> The {@code options} parameter specifies how the file is created3688* or opened. If no options are present then this method works as if the3689* {@link StandardOpenOption#CREATE CREATE}, {@link3690* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3691* StandardOpenOption#WRITE WRITE} options are present. In other words, it3692* opens the file for writing, creating the file if it doesn't exist, or3693* initially truncating an existing {@link #isRegularFile regular-file} to3694* a size of {@code 0}.3695*3696*3697* @param path3698* the path to the file3699* @param csq3700* the CharSequence to be written3701* @param cs3702* the charset to use for encoding3703* @param options3704* options specifying how the file is opened3705*3706* @return the path3707*3708* @throws IllegalArgumentException3709* if {@code options} contains an invalid combination of options3710* @throws IOException3711* if an I/O error occurs writing to or creating the file, or the3712* text cannot be encoded using the specified charset3713* @throws UnsupportedOperationException3714* if an unsupported option is specified3715* @throws SecurityException3716* In the case of the default provider, and a security manager is3717* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3718* method is invoked to check write access to the file. The {@link3719* SecurityManager#checkDelete(String) checkDelete} method is3720* invoked to check delete access if the file is opened with the3721* {@code DELETE_ON_CLOSE} option.3722*3723* @since 113724*/3725public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)3726throws IOException3727{3728// ensure the text is not null before opening file3729Objects.requireNonNull(path);3730Objects.requireNonNull(csq);3731Objects.requireNonNull(cs);37323733byte[] bytes = JLA.getBytesNoRepl(String.valueOf(csq), cs);3734if (path.getClass().getModule() != Object.class.getModule())3735bytes = bytes.clone();3736write(path, bytes, options);37373738return path;3739}37403741// -- Stream APIs --37423743/**3744* Return a lazily populated {@code Stream}, the elements of3745* which are the entries in the directory. The listing is not recursive.3746*3747* <p> The elements of the stream are {@link Path} objects that are3748* obtained as if by {@link Path#resolve(Path) resolving} the name of the3749* directory entry against {@code dir}. Some file systems maintain special3750* links to the directory itself and the directory's parent directory.3751* Entries representing these links are not included.3752*3753* <p> The stream is <i>weakly consistent</i>. It is thread safe but does3754* not freeze the directory while iterating, so it may (or may not)3755* reflect updates to the directory that occur after returning from this3756* method.3757*3758* <p> The returned stream contains a reference to an open directory.3759* The directory is closed by closing the stream.3760*3761* <p> Operating on a closed stream behaves as if the end of stream3762* has been reached. Due to read-ahead, one or more elements may be3763* returned after the stream has been closed.3764*3765* <p> If an {@link IOException} is thrown when accessing the directory3766* after this method has returned, it is wrapped in an {@link3767* UncheckedIOException} which will be thrown from the method that caused3768* the access to take place.3769*3770* @apiNote3771* This method must be used within a try-with-resources statement or similar3772* control structure to ensure that the stream's open directory is closed3773* promptly after the stream's operations have completed.3774*3775* @param dir The path to the directory3776*3777* @return The {@code Stream} describing the content of the3778* directory3779*3780* @throws NotDirectoryException3781* if the file could not otherwise be opened because it is not3782* a directory <i>(optional specific exception)</i>3783* @throws IOException3784* if an I/O error occurs when opening the directory3785* @throws SecurityException3786* In the case of the default provider, and a security manager is3787* installed, the {@link SecurityManager#checkRead(String) checkRead}3788* method is invoked to check read access to the directory.3789*3790* @see #newDirectoryStream(Path)3791* @since 1.83792*/3793public static Stream<Path> list(Path dir) throws IOException {3794DirectoryStream<Path> ds = Files.newDirectoryStream(dir);3795try {3796final Iterator<Path> delegate = ds.iterator();37973798// Re-wrap DirectoryIteratorException to UncheckedIOException3799Iterator<Path> iterator = new Iterator<>() {3800@Override3801public boolean hasNext() {3802try {3803return delegate.hasNext();3804} catch (DirectoryIteratorException e) {3805throw new UncheckedIOException(e.getCause());3806}3807}3808@Override3809public Path next() {3810try {3811return delegate.next();3812} catch (DirectoryIteratorException e) {3813throw new UncheckedIOException(e.getCause());3814}3815}3816};38173818Spliterator<Path> spliterator =3819Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);3820return StreamSupport.stream(spliterator, false)3821.onClose(asUncheckedRunnable(ds));3822} catch (Error|RuntimeException e) {3823try {3824ds.close();3825} catch (IOException ex) {3826try {3827e.addSuppressed(ex);3828} catch (Throwable ignore) {}3829}3830throw e;3831}3832}38333834/**3835* Return a {@code Stream} that is lazily populated with {@code3836* Path} by walking the file tree rooted at a given starting file. The3837* file tree is traversed <em>depth-first</em>, the elements in the stream3838* are {@link Path} objects that are obtained as if by {@link3839* Path#resolve(Path) resolving} the relative path against {@code start}.3840*3841* <p> The {@code stream} walks the file tree as elements are consumed.3842* The {@code Stream} returned is guaranteed to have at least one3843* element, the starting file itself. For each file visited, the stream3844* attempts to read its {@link BasicFileAttributes}. If the file is a3845* directory and can be opened successfully, entries in the directory, and3846* their <em>descendants</em> will follow the directory in the stream as3847* they are encountered. When all entries have been visited, then the3848* directory is closed. The file tree walk then continues at the next3849* <em>sibling</em> of the directory.3850*3851* <p> The stream is <i>weakly consistent</i>. It does not freeze the3852* file tree while iterating, so it may (or may not) reflect updates to3853* the file tree that occur after returned from this method.3854*3855* <p> By default, symbolic links are not automatically followed by this3856* method. If the {@code options} parameter contains the {@link3857* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are3858* followed. When following links, and the attributes of the target cannot3859* be read, then this method attempts to get the {@code BasicFileAttributes}3860* of the link.3861*3862* <p> If the {@code options} parameter contains the {@link3863* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then the stream keeps3864* track of directories visited so that cycles can be detected. A cycle3865* arises when there is an entry in a directory that is an ancestor of the3866* directory. Cycle detection is done by recording the {@link3867* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,3868* or if file keys are not available, by invoking the {@link #isSameFile3869* isSameFile} method to test if a directory is the same file as an3870* ancestor. When a cycle is detected it is treated as an I/O error with3871* an instance of {@link FileSystemLoopException}.3872*3873* <p> The {@code maxDepth} parameter is the maximum number of levels of3874* directories to visit. A value of {@code 0} means that only the starting3875* file is visited, unless denied by the security manager. A value of3876* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all3877* levels should be visited.3878*3879* <p> When a security manager is installed and it denies access to a file3880* (or directory), then it is ignored and not included in the stream.3881*3882* <p> The returned stream contains references to one or more open directories.3883* The directories are closed by closing the stream.3884*3885* <p> If an {@link IOException} is thrown when accessing the directory3886* after this method has returned, it is wrapped in an {@link3887* UncheckedIOException} which will be thrown from the method that caused3888* the access to take place.3889*3890* @apiNote3891* This method must be used within a try-with-resources statement or similar3892* control structure to ensure that the stream's open directories are closed3893* promptly after the stream's operations have completed.3894*3895* @param start3896* the starting file3897* @param maxDepth3898* the maximum number of directory levels to visit3899* @param options3900* options to configure the traversal3901*3902* @return the {@link Stream} of {@link Path}3903*3904* @throws IllegalArgumentException3905* if the {@code maxDepth} parameter is negative3906* @throws SecurityException3907* If the security manager denies access to the starting file.3908* In the case of the default provider, the {@link3909* SecurityManager#checkRead(String) checkRead} method is invoked3910* to check read access to the directory.3911* @throws IOException3912* if an I/O error is thrown when accessing the starting file.3913* @since 1.83914*/3915public static Stream<Path> walk(Path start,3916int maxDepth,3917FileVisitOption... options)3918throws IOException3919{3920FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);3921try {3922Spliterator<FileTreeWalker.Event> spliterator =3923Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);3924return StreamSupport.stream(spliterator, false)3925.onClose(iterator::close)3926.map(entry -> entry.file());3927} catch (Error|RuntimeException e) {3928iterator.close();3929throw e;3930}3931}39323933/**3934* Return a {@code Stream} that is lazily populated with {@code3935* Path} by walking the file tree rooted at a given starting file. The3936* file tree is traversed <em>depth-first</em>, the elements in the stream3937* are {@link Path} objects that are obtained as if by {@link3938* Path#resolve(Path) resolving} the relative path against {@code start}.3939*3940* <p> This method works as if invoking it were equivalent to evaluating the3941* expression:3942* <blockquote>{@link3943* walk(Path, int, FileVisitOption...)3944* Files.walk(start, Integer.MAX_VALUE, options)3945* }</blockquote>3946* In other words, it visits all levels of the file tree.3947*3948* <p> The returned stream contains references to one or more open directories.3949* The directories are closed by closing the stream.3950*3951* @apiNote3952* This method must be used within a try-with-resources statement or similar3953* control structure to ensure that the stream's open directories are closed3954* promptly after the stream's operations have completed.3955*3956* @param start3957* the starting file3958* @param options3959* options to configure the traversal3960*3961* @return the {@link Stream} of {@link Path}3962*3963* @throws SecurityException3964* If the security manager denies access to the starting file.3965* In the case of the default provider, the {@link3966* SecurityManager#checkRead(String) checkRead} method is invoked3967* to check read access to the directory.3968* @throws IOException3969* if an I/O error is thrown when accessing the starting file.3970*3971* @see #walk(Path, int, FileVisitOption...)3972* @since 1.83973*/3974public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException {3975return walk(start, Integer.MAX_VALUE, options);3976}39773978/**3979* Return a {@code Stream} that is lazily populated with {@code3980* Path} by searching for files in a file tree rooted at a given starting3981* file.3982*3983* <p> This method walks the file tree in exactly the manner specified by3984* the {@link #walk walk} method. For each file encountered, the given3985* {@link BiPredicate} is invoked with its {@link Path} and {@link3986* BasicFileAttributes}. The {@code Path} object is obtained as if by3987* {@link Path#resolve(Path) resolving} the relative path against {@code3988* start} and is only included in the returned {@link Stream} if3989* the {@code BiPredicate} returns true. Compare to calling {@link3990* java.util.stream.Stream#filter filter} on the {@code Stream}3991* returned by {@code walk} method, this method may be more efficient by3992* avoiding redundant retrieval of the {@code BasicFileAttributes}.3993*3994* <p> The returned stream contains references to one or more open directories.3995* The directories are closed by closing the stream.3996*3997* <p> If an {@link IOException} is thrown when accessing the directory3998* after returned from this method, it is wrapped in an {@link3999* UncheckedIOException} which will be thrown from the method that caused4000* the access to take place.4001*4002* @apiNote4003* This method must be used within a try-with-resources statement or similar4004* control structure to ensure that the stream's open directories are closed4005* promptly after the stream's operations have completed.4006*4007* @param start4008* the starting file4009* @param maxDepth4010* the maximum number of directory levels to search4011* @param matcher4012* the function used to decide whether a file should be included4013* in the returned stream4014* @param options4015* options to configure the traversal4016*4017* @return the {@link Stream} of {@link Path}4018*4019* @throws IllegalArgumentException4020* if the {@code maxDepth} parameter is negative4021* @throws SecurityException4022* If the security manager denies access to the starting file.4023* In the case of the default provider, the {@link4024* SecurityManager#checkRead(String) checkRead} method is invoked4025* to check read access to the directory.4026* @throws IOException4027* if an I/O error is thrown when accessing the starting file.4028*4029* @see #walk(Path, int, FileVisitOption...)4030* @since 1.84031*/4032public static Stream<Path> find(Path start,4033int maxDepth,4034BiPredicate<Path, BasicFileAttributes> matcher,4035FileVisitOption... options)4036throws IOException4037{4038FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);4039try {4040Spliterator<FileTreeWalker.Event> spliterator =4041Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);4042return StreamSupport.stream(spliterator, false)4043.onClose(iterator::close)4044.filter(entry -> matcher.test(entry.file(), entry.attributes()))4045.map(entry -> entry.file());4046} catch (Error|RuntimeException e) {4047iterator.close();4048throw e;4049}4050}405140524053/**4054* Read all lines from a file as a {@code Stream}. Unlike {@link4055* #readAllLines(Path, Charset) readAllLines}, this method does not read4056* all lines into a {@code List}, but instead populates lazily as the stream4057* is consumed.4058*4059* <p> Bytes from the file are decoded into characters using the specified4060* charset and the same line terminators as specified by {@code4061* readAllLines} are supported.4062*4063* <p> The returned stream contains a reference to an open file. The file4064* is closed by closing the stream.4065*4066* <p> The file contents should not be modified during the execution of the4067* terminal stream operation. Otherwise, the result of the terminal stream4068* operation is undefined.4069*4070* <p> After this method returns, then any subsequent I/O exception that4071* occurs while reading from the file or when a malformed or unmappable byte4072* sequence is read, is wrapped in an {@link UncheckedIOException} that will4073* be thrown from the4074* {@link java.util.stream.Stream} method that caused the read to take4075* place. In case an {@code IOException} is thrown when closing the file,4076* it is also wrapped as an {@code UncheckedIOException}.4077*4078* @apiNote4079* This method must be used within a try-with-resources statement or similar4080* control structure to ensure that the stream's open file is closed promptly4081* after the stream's operations have completed.4082*4083* @implNote4084* This implementation supports good parallel stream performance for the4085* standard charsets {@link StandardCharsets#UTF_8 UTF-8},4086* {@link StandardCharsets#US_ASCII US-ASCII} and4087* {@link StandardCharsets#ISO_8859_1 ISO-8859-1}. Such4088* <em>line-optimal</em> charsets have the property that the encoded bytes4089* of a line feed ('\n') or a carriage return ('\r') are efficiently4090* identifiable from other encoded characters when randomly accessing the4091* bytes of the file.4092*4093* <p> For non-<em>line-optimal</em> charsets the stream source's4094* spliterator has poor splitting properties, similar to that of a4095* spliterator associated with an iterator or that associated with a stream4096* returned from {@link BufferedReader#lines()}. Poor splitting properties4097* can result in poor parallel stream performance.4098*4099* <p> For <em>line-optimal</em> charsets the stream source's spliterator4100* has good splitting properties, assuming the file contains a regular4101* sequence of lines. Good splitting properties can result in good parallel4102* stream performance. The spliterator for a <em>line-optimal</em> charset4103* takes advantage of the charset properties (a line feed or a carriage4104* return being efficient identifiable) such that when splitting it can4105* approximately divide the number of covered lines in half.4106*4107* @param path4108* the path to the file4109* @param cs4110* the charset to use for decoding4111*4112* @return the lines from the file as a {@code Stream}4113*4114* @throws IOException4115* if an I/O error occurs opening the file4116* @throws SecurityException4117* In the case of the default provider, and a security manager is4118* installed, the {@link SecurityManager#checkRead(String) checkRead}4119* method is invoked to check read access to the file.4120*4121* @see #readAllLines(Path, Charset)4122* @see #newBufferedReader(Path, Charset)4123* @see java.io.BufferedReader#lines()4124* @since 1.84125*/4126public static Stream<String> lines(Path path, Charset cs) throws IOException {4127// Use the good splitting spliterator if:4128// 1) the path is associated with the default file system;4129// 2) the character set is supported; and4130// 3) the file size is such that all bytes can be indexed by int values4131// (this limitation is imposed by ByteBuffer)4132if (path.getFileSystem() == FileSystems.getDefault() &&4133FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) {4134FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);41354136Stream<String> fcls = createFileChannelLinesStream(fc, cs);4137if (fcls != null) {4138return fcls;4139}4140fc.close();4141}41424143return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs));4144}41454146private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException {4147try {4148// Obtaining the size from the FileChannel is much faster4149// than obtaining using path.toFile().length()4150long length = fc.size();4151// FileChannel.size() may in certain circumstances return zero4152// for a non-zero length file so disallow this case.4153if (length > 0 && length <= Integer.MAX_VALUE) {4154FileChannelLinesSpliterator fcls =4155new FileChannelLinesSpliterator(fc, cs, 0, (int) length);4156return StreamSupport.stream(fcls, false)4157.onClose(Files.asUncheckedRunnable(fc))4158.onClose(() -> fcls.close());4159}4160} catch (Error|RuntimeException|IOException e) {4161try {4162fc.close();4163} catch (IOException ex) {4164try {4165e.addSuppressed(ex);4166} catch (Throwable ignore) {4167}4168}4169throw e;4170}4171return null;4172}41734174private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) {4175try {4176return br.lines().onClose(asUncheckedRunnable(br));4177} catch (Error|RuntimeException e) {4178try {4179br.close();4180} catch (IOException ex) {4181try {4182e.addSuppressed(ex);4183} catch (Throwable ignore) {4184}4185}4186throw e;4187}4188}41894190/**4191* Read all lines from a file as a {@code Stream}. Bytes from the file are4192* decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8}4193* {@link Charset charset}.4194*4195* <p> The returned stream contains a reference to an open file. The file4196* is closed by closing the stream.4197*4198* <p> The file contents should not be modified during the execution of the4199* terminal stream operation. Otherwise, the result of the terminal stream4200* operation is undefined.4201*4202* <p> This method works as if invoking it were equivalent to evaluating the4203* expression:4204* <blockquote>{@link4205* lines(Path, Charset)4206* Files.lines(path, StandardCharsets.UTF_8)4207* }</blockquote>4208*4209* @apiNote4210* This method must be used within a try-with-resources statement or similar4211* control structure to ensure that the stream's open file is closed promptly4212* after the stream's operations have completed.4213*4214* @param path4215* the path to the file4216*4217* @return the lines from the file as a {@code Stream}4218*4219* @throws IOException4220* if an I/O error occurs opening the file4221* @throws SecurityException4222* In the case of the default provider, and a security manager is4223* installed, the {@link SecurityManager#checkRead(String) checkRead}4224* method is invoked to check read access to the file.4225*4226* @since 1.84227*/4228public static Stream<String> lines(Path path) throws IOException {4229return lines(path, UTF_8.INSTANCE);4230}4231}423242334234