Path: blob/master/src/java.base/share/classes/java/nio/file/Files.java
67794 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 = switch (ev.type()) {2806case ENTRY -> {2807IOException ioe = ev.ioeException();2808if (ioe == null) {2809assert ev.attributes() != null;2810yield visitor.visitFile(ev.file(), ev.attributes());2811} else {2812yield visitor.visitFileFailed(ev.file(), ioe);2813}2814}2815case START_DIRECTORY -> {2816var res = visitor.preVisitDirectory(ev.file(), ev.attributes());28172818// if SKIP_SIBLINGS and SKIP_SUBTREE is returned then2819// there shouldn't be any more events for the current2820// directory.2821if (res == FileVisitResult.SKIP_SUBTREE ||2822res == FileVisitResult.SKIP_SIBLINGS)2823walker.pop();2824yield res;2825}2826case END_DIRECTORY -> {2827var res = visitor.postVisitDirectory(ev.file(), ev.ioeException());28282829// SKIP_SIBLINGS is a no-op for postVisitDirectory2830if (res == FileVisitResult.SKIP_SIBLINGS)2831res = FileVisitResult.CONTINUE;2832yield res;2833}2834default -> throw new AssertionError("Should not get here");2835};28362837if (Objects.requireNonNull(result) != FileVisitResult.CONTINUE) {2838if (result == FileVisitResult.TERMINATE) {2839break;2840} else if (result == FileVisitResult.SKIP_SIBLINGS) {2841walker.skipRemainingSiblings();2842}2843}2844ev = walker.next();2845} while (ev != null);2846}28472848return start;2849}28502851/**2852* Walks a file tree.2853*2854* <p> This method works as if invoking it were equivalent to evaluating the2855* expression:2856* <blockquote>{@link2857* walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor<? super Path>)2858* Files.walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)2859* }</blockquote>2860* In other words, it does not follow symbolic links, and visits all levels2861* of the file tree.2862*2863* @param start2864* the starting file2865* @param visitor2866* the file visitor to invoke for each file2867*2868* @return the starting file2869*2870* @throws SecurityException2871* If the security manager denies access to the starting file.2872* In the case of the default provider, the {@link2873* SecurityManager#checkRead(String) checkRead} method is invoked2874* to check read access to the directory.2875* @throws IOException2876* if an I/O error is thrown by a visitor method2877*/2878public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)2879throws IOException2880{2881return walkFileTree(start,2882EnumSet.noneOf(FileVisitOption.class),2883Integer.MAX_VALUE,2884visitor);2885}288628872888// -- Utility methods for simple usages --288928902891/**2892* Opens a file for reading, returning a {@code BufferedReader} that may be2893* used to read text from the file in an efficient manner. Bytes from the2894* file are decoded into characters using the specified charset. Reading2895* commences at the beginning of the file.2896*2897* <p> The {@code Reader} methods that read from the file throw {@code2898* IOException} if a malformed or unmappable byte sequence is read.2899*2900* @param path2901* the path to the file2902* @param cs2903* the charset to use for decoding2904*2905* @return a new buffered reader, with default buffer size, to read text2906* from the file2907*2908* @throws IOException2909* if an I/O error occurs opening the file2910* @throws SecurityException2911* In the case of the default provider, and a security manager is2912* installed, the {@link SecurityManager#checkRead(String) checkRead}2913* method is invoked to check read access to the file.2914*2915* @see #readAllLines2916*/2917public static BufferedReader newBufferedReader(Path path, Charset cs)2918throws IOException2919{2920CharsetDecoder decoder = cs.newDecoder();2921Reader reader = new InputStreamReader(newInputStream(path), decoder);2922return new BufferedReader(reader);2923}29242925/**2926* Opens a file for reading, returning a {@code BufferedReader} to read text2927* from the file in an efficient manner. Bytes from the file are decoded into2928* characters using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset2929* charset}.2930*2931* <p> This method works as if invoking it were equivalent to evaluating the2932* expression:2933* <blockquote>{@link2934* newBufferedReader(Path, Charset)2935* Files.newBufferedReader(path, StandardCharsets.UTF_8)2936* }</blockquote>2937*2938* @param path2939* the path to the file2940*2941* @return a new buffered reader, with default buffer size, to read text2942* from the file2943*2944* @throws IOException2945* if an I/O error occurs opening the file2946* @throws SecurityException2947* In the case of the default provider, and a security manager is2948* installed, the {@link SecurityManager#checkRead(String) checkRead}2949* method is invoked to check read access to the file.2950*2951* @since 1.82952*/2953public static BufferedReader newBufferedReader(Path path) throws IOException {2954return newBufferedReader(path, UTF_8.INSTANCE);2955}29562957/**2958* Opens or creates a file for writing, returning a {@code BufferedWriter}2959* that may be used to write text to the file in an efficient manner.2960* The {@code options} parameter specifies how the file is created or2961* opened. If no options are present then this method works as if the {@link2962* StandardOpenOption#CREATE CREATE}, {@link2963* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link2964* StandardOpenOption#WRITE WRITE} options are present. In other words, it2965* opens the file for writing, creating the file if it doesn't exist, or2966* initially truncating an existing {@link #isRegularFile regular-file} to2967* a size of {@code 0} if it exists.2968*2969* <p> The {@code Writer} methods to write text throw {@code IOException}2970* if the text cannot be encoded using the specified charset.2971*2972* @param path2973* the path to the file2974* @param cs2975* the charset to use for encoding2976* @param options2977* options specifying how the file is opened2978*2979* @return a new buffered writer, with default buffer size, to write text2980* to the file2981*2982* @throws IllegalArgumentException2983* if {@code options} contains an invalid combination of options2984* @throws IOException2985* if an I/O error occurs opening or creating the file2986* @throws UnsupportedOperationException2987* if an unsupported option is specified2988* @throws FileAlreadyExistsException2989* If a file of that name already exists and the {@link2990* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified2991* <i>(optional specific exception)</i>2992* @throws SecurityException2993* In the case of the default provider, and a security manager is2994* installed, the {@link SecurityManager#checkWrite(String) checkWrite}2995* method is invoked to check write access to the file. The {@link2996* SecurityManager#checkDelete(String) checkDelete} method is2997* invoked to check delete access if the file is opened with the2998* {@code DELETE_ON_CLOSE} option.2999*3000* @see #write(Path,Iterable,Charset,OpenOption[])3001*/3002public static BufferedWriter newBufferedWriter(Path path, Charset cs,3003OpenOption... options)3004throws IOException3005{3006CharsetEncoder encoder = cs.newEncoder();3007Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder);3008return new BufferedWriter(writer);3009}30103011/**3012* Opens or creates a file for writing, returning a {@code BufferedWriter}3013* to write text to the file in an efficient manner. The text is encoded3014* into bytes for writing using the {@link StandardCharsets#UTF_8 UTF-8}3015* {@link Charset charset}.3016*3017* <p> This method works as if invoking it were equivalent to evaluating the3018* expression:3019* <blockquote>{@link3020* newBufferedWriter(Path, Charset, OpenOption...)3021* Files.newBufferedWriter(path, StandardCharsets.UTF_8, options)3022* }</blockquote>3023*3024* @param path3025* the path to the file3026* @param options3027* options specifying how the file is opened3028*3029* @return a new buffered writer, with default buffer size, to write text3030* to the file3031*3032* @throws IllegalArgumentException3033* if {@code options} contains an invalid combination of options3034* @throws IOException3035* if an I/O error occurs opening or creating the file3036* @throws UnsupportedOperationException3037* if an unsupported option is specified3038* @throws FileAlreadyExistsException3039* If a file of that name already exists and the {@link3040* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3041* <i>(optional specific exception)</i>3042* @throws SecurityException3043* In the case of the default provider, and a security manager is3044* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3045* method is invoked to check write access to the file. The {@link3046* SecurityManager#checkDelete(String) checkDelete} method is3047* invoked to check delete access if the file is opened with the3048* {@code DELETE_ON_CLOSE} option.3049*3050* @since 1.83051*/3052public static BufferedWriter newBufferedWriter(Path path, OpenOption... options)3053throws IOException3054{3055return newBufferedWriter(path, UTF_8.INSTANCE, options);3056}30573058/**3059* Copies all bytes from an input stream to a file. On return, the input3060* stream will be at end of stream.3061*3062* <p> By default, the copy fails if the target file already exists or is a3063* symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING3064* REPLACE_EXISTING} option is specified, and the target file already exists,3065* then it is replaced if it is not a non-empty directory. If the target3066* file exists and is a symbolic link, then the symbolic link is replaced.3067* In this release, the {@code REPLACE_EXISTING} option is the only option3068* required to be supported by this method. Additional options may be3069* supported in future releases.3070*3071* <p> If an I/O error occurs reading from the input stream or writing to3072* the file, then it may do so after the target file has been created and3073* after some bytes have been read or written. Consequently the input3074* stream may not be at end of stream and may be in an inconsistent state.3075* It is strongly recommended that the input stream be promptly closed if an3076* I/O error occurs.3077*3078* <p> This method may block indefinitely reading from the input stream (or3079* writing to the file). The behavior for the case that the input stream is3080* <i>asynchronously closed</i> or the thread interrupted during the copy is3081* highly input stream and file system provider specific and therefore not3082* specified.3083*3084* <p> <b>Usage example</b>: Suppose we want to capture a web page and save3085* it to a file:3086* <pre>3087* Path path = ...3088* URI u = URI.create("http://www.example.com/");3089* try (InputStream in = u.toURL().openStream()) {3090* Files.copy(in, path);3091* }3092* </pre>3093*3094* @param in3095* the input stream to read from3096* @param target3097* the path to the file3098* @param options3099* options specifying how the copy should be done3100*3101* @return the number of bytes read or written3102*3103* @throws IOException3104* if an I/O error occurs when reading or writing3105* @throws FileAlreadyExistsException3106* if the target file exists but cannot be replaced because the3107* {@code REPLACE_EXISTING} option is not specified <i>(optional3108* specific exception)</i>3109* @throws DirectoryNotEmptyException3110* the {@code REPLACE_EXISTING} option is specified but the file3111* cannot be replaced because it is a non-empty directory3112* <i>(optional specific exception)</i> *3113* @throws UnsupportedOperationException3114* if {@code options} contains a copy option that is not supported3115* @throws SecurityException3116* In the case of the default provider, and a security manager is3117* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3118* method is invoked to check write access to the file. Where the3119* {@code REPLACE_EXISTING} option is specified, the security3120* manager's {@link SecurityManager#checkDelete(String) checkDelete}3121* method is invoked to check that an existing file can be deleted.3122*/3123public static long copy(InputStream in, Path target, CopyOption... options)3124throws IOException3125{3126// ensure not null before opening file3127Objects.requireNonNull(in);31283129// check for REPLACE_EXISTING3130boolean replaceExisting = false;3131for (CopyOption opt: options) {3132if (opt == StandardCopyOption.REPLACE_EXISTING) {3133replaceExisting = true;3134} else {3135if (opt == null) {3136throw new NullPointerException("options contains 'null'");3137} else {3138throw new UnsupportedOperationException(opt + " not supported");3139}3140}3141}31423143// attempt to delete an existing file3144SecurityException se = null;3145if (replaceExisting) {3146try {3147deleteIfExists(target);3148} catch (SecurityException x) {3149se = x;3150}3151}31523153// attempt to create target file. If it fails with3154// FileAlreadyExistsException then it may be because the security3155// manager prevented us from deleting the file, in which case we just3156// throw the SecurityException.3157OutputStream ostream;3158try {3159ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,3160StandardOpenOption.WRITE);3161} catch (FileAlreadyExistsException x) {3162if (se != null)3163throw se;3164// someone else won the race and created the file3165throw x;3166}31673168// do the copy3169try (OutputStream out = ostream) {3170return in.transferTo(out);3171}3172}31733174/**3175* Copies all bytes from a file to an output stream.3176*3177* <p> If an I/O error occurs reading from the file or writing to the output3178* stream, then it may do so after some bytes have been read or written.3179* Consequently the output stream may be in an inconsistent state. It is3180* strongly recommended that the output stream be promptly closed if an I/O3181* error occurs.3182*3183* <p> This method may block indefinitely writing to the output stream (or3184* reading from the file). The behavior for the case that the output stream3185* is <i>asynchronously closed</i> or the thread interrupted during the copy3186* is highly output stream and file system provider specific and therefore3187* not specified.3188*3189* <p> Note that if the given output stream is {@link java.io.Flushable}3190* then its {@link java.io.Flushable#flush flush} method may need to invoked3191* after this method completes so as to flush any buffered output.3192*3193* @param source3194* the path to the file3195* @param out3196* the output stream to write to3197*3198* @return the number of bytes read or written3199*3200* @throws IOException3201* if an I/O error occurs when reading or writing3202* @throws SecurityException3203* In the case of the default provider, and a security manager is3204* installed, the {@link SecurityManager#checkRead(String) checkRead}3205* method is invoked to check read access to the file.3206*/3207public static long copy(Path source, OutputStream out) throws IOException {3208// ensure not null before opening file3209Objects.requireNonNull(out);32103211try (InputStream in = newInputStream(source)) {3212return in.transferTo(out);3213}3214}32153216private static final jdk.internal.access.JavaLangAccess JLA =3217jdk.internal.access.SharedSecrets.getJavaLangAccess();32183219/**3220* Reads all the bytes from an input stream. Uses {@code initialSize} as a hint3221* about how many bytes the stream will have.3222*3223* @param source3224* the input stream to read from3225* @param initialSize3226* the initial size of the byte array to allocate3227*3228* @return a byte array containing the bytes read from the file3229*3230* @throws IOException3231* if an I/O error occurs reading from the stream3232* @throws OutOfMemoryError3233* if an array of the required size cannot be allocated3234*/3235private static byte[] read(InputStream source, int initialSize) throws IOException {3236int capacity = initialSize;3237byte[] buf = new byte[capacity];3238int nread = 0;3239int n;3240for (;;) {3241// read to EOF which may read more or less than initialSize (eg: file3242// is truncated while we are reading)3243while ((n = source.read(buf, nread, capacity - nread)) > 0)3244nread += n;32453246// if last call to source.read() returned -1, we are done3247// otherwise, try to read one more byte; if that failed we're done too3248if (n < 0 || (n = source.read()) < 0)3249break;32503251// one more byte was read; need to allocate a larger buffer3252capacity = Math.max(ArraysSupport.newLength(capacity,32531, /* minimum growth */3254capacity /* preferred growth */),3255BUFFER_SIZE);3256buf = Arrays.copyOf(buf, capacity);3257buf[nread++] = (byte)n;3258}3259return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);3260}32613262/**3263* Reads all the bytes from a file. The method ensures that the file is3264* closed when all bytes have been read or an I/O error, or other runtime3265* exception, is thrown.3266*3267* <p> Note that this method is intended for simple cases where it is3268* convenient to read all bytes into a byte array. It is not intended for3269* reading in large files.3270*3271* @param path3272* the path to the file3273*3274* @return a byte array containing the bytes read from the file3275*3276* @throws IOException3277* if an I/O error occurs reading from the stream3278* @throws OutOfMemoryError3279* if an array of the required size cannot be allocated, for3280* example the file is larger that {@code 2GB}3281* @throws SecurityException3282* In the case of the default provider, and a security manager is3283* installed, the {@link SecurityManager#checkRead(String) checkRead}3284* method is invoked to check read access to the file.3285*/3286public static byte[] readAllBytes(Path path) throws IOException {3287try (SeekableByteChannel sbc = Files.newByteChannel(path);3288InputStream in = Channels.newInputStream(sbc)) {3289if (sbc instanceof FileChannelImpl)3290((FileChannelImpl) sbc).setUninterruptible();3291long size = sbc.size();3292if (size > (long) Integer.MAX_VALUE)3293throw new OutOfMemoryError("Required array size too large");3294return read(in, (int)size);3295}3296}32973298/**3299* Reads all content from a file into a string, decoding from bytes to characters3300* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3301* The method ensures that the file is closed when all content have been read3302* or an I/O error, or other runtime exception, is thrown.3303*3304* <p> This method is equivalent to: {@link readString(Path, Charset)3305* readString(path, StandardCharsets.UTF_8)}.3306*3307* @param path the path to the file3308*3309* @return a String containing the content read from the file3310*3311* @throws IOException3312* if an I/O error occurs reading from the file or a malformed or3313* unmappable byte sequence is read3314* @throws OutOfMemoryError3315* if the file is extremely large, for example larger than {@code 2GB}3316* @throws SecurityException3317* In the case of the default provider, and a security manager is3318* installed, the {@link SecurityManager#checkRead(String) checkRead}3319* method is invoked to check read access to the file.3320*3321* @since 113322*/3323public static String readString(Path path) throws IOException {3324return readString(path, UTF_8.INSTANCE);3325}33263327/**3328* Reads all characters from a file into a string, decoding from bytes to characters3329* using the specified {@linkplain Charset charset}.3330* The method ensures that the file is closed when all content have been read3331* or an I/O error, or other runtime exception, is thrown.3332*3333* <p> This method reads all content including the line separators in the middle3334* and/or at the end. The resulting string will contain line separators as they3335* appear in the file.3336*3337* @apiNote3338* This method is intended for simple cases where it is appropriate and convenient3339* to read the content of a file into a String. It is not intended for reading3340* very large files.3341*3342*3343*3344* @param path the path to the file3345* @param cs the charset to use for decoding3346*3347* @return a String containing the content read from the file3348*3349* @throws IOException3350* if an I/O error occurs reading from the file or a malformed or3351* unmappable byte sequence is read3352* @throws OutOfMemoryError3353* if the file is extremely large, for example larger than {@code 2GB}3354* @throws SecurityException3355* In the case of the default provider, and a security manager is3356* installed, the {@link SecurityManager#checkRead(String) checkRead}3357* method is invoked to check read access to the file.3358*3359* @since 113360*/3361public static String readString(Path path, Charset cs) throws IOException {3362Objects.requireNonNull(path);3363Objects.requireNonNull(cs);33643365byte[] ba = readAllBytes(path);3366if (path.getClass().getModule() != Object.class.getModule())3367ba = ba.clone();3368return JLA.newStringNoRepl(ba, cs);3369}33703371/**3372* Read all lines from a file. This method ensures that the file is3373* closed when all bytes have been read or an I/O error, or other runtime3374* exception, is thrown. Bytes from the file are decoded into characters3375* using the specified charset.3376*3377* <p> This method recognizes the following as line terminators:3378* <ul>3379* <li> <code>\u000D</code> followed by <code>\u000A</code>,3380* CARRIAGE RETURN followed by LINE FEED </li>3381* <li> <code>\u000A</code>, LINE FEED </li>3382* <li> <code>\u000D</code>, CARRIAGE RETURN </li>3383* </ul>3384* <p> Additional Unicode line terminators may be recognized in future3385* releases.3386*3387* <p> Note that this method is intended for simple cases where it is3388* convenient to read all lines in a single operation. It is not intended3389* for reading in large files.3390*3391* @param path3392* the path to the file3393* @param cs3394* the charset to use for decoding3395*3396* @return the lines from the file as a {@code List}; whether the {@code3397* List} is modifiable or not is implementation dependent and3398* therefore not specified3399*3400* @throws IOException3401* if an I/O error occurs reading from the file or a malformed or3402* unmappable byte sequence is read3403* @throws SecurityException3404* In the case of the default provider, and a security manager is3405* installed, the {@link SecurityManager#checkRead(String) checkRead}3406* method is invoked to check read access to the file.3407*3408* @see #newBufferedReader3409*/3410public static List<String> readAllLines(Path path, Charset cs) throws IOException {3411try (BufferedReader reader = newBufferedReader(path, cs)) {3412List<String> result = new ArrayList<>();3413for (;;) {3414String line = reader.readLine();3415if (line == null)3416break;3417result.add(line);3418}3419return result;3420}3421}34223423/**3424* Read all lines from a file. Bytes from the file are decoded into characters3425* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3426*3427* <p> This method works as if invoking it were equivalent to evaluating the3428* expression:3429* <blockquote>{@link3430* readAllLines(Path, Charset)3431* Files.readAllLines(path, StandardCharsets.UTF_8)3432* }</blockquote>3433*3434* @param path3435* the path to the file3436*3437* @return the lines from the file as a {@code List}; whether the {@code3438* List} is modifiable or not is implementation dependent and3439* therefore not specified3440*3441* @throws IOException3442* if an I/O error occurs reading from the file or a malformed or3443* unmappable byte sequence is read3444* @throws SecurityException3445* In the case of the default provider, and a security manager is3446* installed, the {@link SecurityManager#checkRead(String) checkRead}3447* method is invoked to check read access to the file.3448*3449* @since 1.83450*/3451public static List<String> readAllLines(Path path) throws IOException {3452return readAllLines(path, UTF_8.INSTANCE);3453}34543455/**3456* Writes bytes to a file. The {@code options} parameter specifies how3457* the file is created or opened. If no options are present then this method3458* works as if the {@link StandardOpenOption#CREATE CREATE}, {@link3459* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3460* StandardOpenOption#WRITE WRITE} options are present. In other words, it3461* opens the file for writing, creating the file if it doesn't exist, or3462* initially truncating an existing {@link #isRegularFile regular-file} to3463* a size of {@code 0}. All bytes in the byte array are written to the file.3464* The method ensures that the file is closed when all bytes have been3465* written (or an I/O error or other runtime exception is thrown). If an I/O3466* error occurs then it may do so after the file has been created or3467* truncated, or after some bytes have been written to the file.3468*3469* <p> <b>Usage example</b>: By default the method creates a new file or3470* overwrites an existing file. Suppose you instead want to append bytes3471* to an existing file:3472* <pre>3473* Path path = ...3474* byte[] bytes = ...3475* Files.write(path, bytes, StandardOpenOption.APPEND);3476* </pre>3477*3478* @param path3479* the path to the file3480* @param bytes3481* the byte array with the bytes to write3482* @param options3483* options specifying how the file is opened3484*3485* @return the path3486*3487* @throws IllegalArgumentException3488* if {@code options} contains an invalid combination of options3489* @throws IOException3490* if an I/O error occurs writing to or creating the file3491* @throws UnsupportedOperationException3492* if an unsupported option is specified3493* @throws FileAlreadyExistsException3494* If a file of that name already exists and the {@link3495* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3496* <i>(optional specific exception)</i>3497* @throws SecurityException3498* In the case of the default provider, and a security manager is3499* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3500* method is invoked to check write access to the file. The {@link3501* SecurityManager#checkDelete(String) checkDelete} method is3502* invoked to check delete access if the file is opened with the3503* {@code DELETE_ON_CLOSE} option.3504*/3505public static Path write(Path path, byte[] bytes, OpenOption... options)3506throws IOException3507{3508// ensure bytes is not null before opening file3509Objects.requireNonNull(bytes);35103511try (OutputStream out = Files.newOutputStream(path, options)) {3512int len = bytes.length;3513int rem = len;3514while (rem > 0) {3515int n = Math.min(rem, BUFFER_SIZE);3516out.write(bytes, (len-rem), n);3517rem -= n;3518}3519}3520return path;3521}35223523/**3524* Write lines of text to a file. Each line is a char sequence and is3525* written to the file in sequence with each line terminated by the3526* platform's line separator, as defined by the system property {@code3527* line.separator}. Characters are encoded into bytes using the specified3528* charset.3529*3530* <p> The {@code options} parameter specifies how the file is created3531* or opened. If no options are present then this method works as if the3532* {@link StandardOpenOption#CREATE CREATE}, {@link3533* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3534* StandardOpenOption#WRITE WRITE} options are present. In other words, it3535* opens the file for writing, creating the file if it doesn't exist, or3536* initially truncating an existing {@link #isRegularFile regular-file} to3537* a size of {@code 0}. The method ensures that the file is closed when all3538* lines have been written (or an I/O error or other runtime exception is3539* thrown). If an I/O error occurs then it may do so after the file has3540* been created or truncated, or after some bytes have been written to the3541* file.3542*3543* @param path3544* the path to the file3545* @param lines3546* an object to iterate over the char sequences3547* @param cs3548* the charset to use for encoding3549* @param options3550* options specifying how the file is opened3551*3552* @return the path3553*3554* @throws IllegalArgumentException3555* if {@code options} contains an invalid combination of options3556* @throws IOException3557* if an I/O error occurs writing to or creating the file, or the3558* text cannot be encoded using the specified charset3559* @throws UnsupportedOperationException3560* if an unsupported option is specified3561* @throws FileAlreadyExistsException3562* If a file of that name already exists and the {@link3563* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified3564* <i>(optional specific exception)</i>3565* @throws SecurityException3566* In the case of the default provider, and a security manager is3567* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3568* method is invoked to check write access to the file. The {@link3569* SecurityManager#checkDelete(String) checkDelete} method is3570* invoked to check delete access if the file is opened with the3571* {@code DELETE_ON_CLOSE} option.3572*/3573public static Path write(Path path, Iterable<? extends CharSequence> lines,3574Charset cs, OpenOption... options)3575throws IOException3576{3577// ensure lines is not null before opening file3578Objects.requireNonNull(lines);3579CharsetEncoder encoder = cs.newEncoder();3580try (OutputStream out = newOutputStream(path, options);3581BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {3582for (CharSequence line: lines) {3583writer.append(line);3584writer.newLine();3585}3586}3587return path;3588}35893590/**3591* Write lines of text to a file. Characters are encoded into bytes using3592* the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3593*3594* <p> This method works as if invoking it were equivalent to evaluating the3595* expression:3596* <blockquote>{@link3597* write(Path, Iterable<? extends CharSequence>, Charset, OpenOption...)3598* Files.write(path, lines, StandardCharsets.UTF_8, options)3599* }</blockquote>3600*3601* @param path3602* the path to the file3603* @param lines3604* an object to iterate over the char sequences3605* @param options3606* options specifying how the file is opened3607*3608* @return the path3609*3610* @throws IllegalArgumentException3611* if {@code options} contains an invalid combination of options3612* @throws IOException3613* if an I/O error occurs writing to or creating the file, or the3614* text cannot be encoded as {@code UTF-8}3615* @throws UnsupportedOperationException3616* if an unsupported option is specified3617* @throws SecurityException3618* In the case of the default provider, and a security manager is3619* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3620* method is invoked to check write access to the file. The {@link3621* SecurityManager#checkDelete(String) checkDelete} method is3622* invoked to check delete access if the file is opened with the3623* {@code DELETE_ON_CLOSE} option.3624*3625* @since 1.83626*/3627public static Path write(Path path,3628Iterable<? extends CharSequence> lines,3629OpenOption... options)3630throws IOException3631{3632return write(path, lines, UTF_8.INSTANCE, options);3633}36343635/**3636* Write a {@linkplain java.lang.CharSequence CharSequence} to a file.3637* Characters are encoded into bytes using the3638* {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.3639*3640* <p> This method is equivalent to: {@link3641* writeString(Path, CharSequence, Charset, OpenOption...)3642* writeString(path, csq, StandardCharsets.UTF_8, options)}.3643*3644* @param path3645* the path to the file3646* @param csq3647* the CharSequence to be written3648* @param options3649* options specifying how the file is opened3650*3651* @return the path3652*3653* @throws IllegalArgumentException3654* if {@code options} contains an invalid combination of options3655* @throws IOException3656* if an I/O error occurs writing to or creating the file, or the3657* text cannot be encoded using the specified charset3658* @throws UnsupportedOperationException3659* if an unsupported option is specified3660* @throws SecurityException3661* In the case of the default provider, and a security manager is3662* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3663* method is invoked to check write access to the file. The {@link3664* SecurityManager#checkDelete(String) checkDelete} method is3665* invoked to check delete access if the file is opened with the3666* {@code DELETE_ON_CLOSE} option.3667*3668* @since 113669*/3670public static Path writeString(Path path, CharSequence csq, OpenOption... options)3671throws IOException3672{3673return writeString(path, csq, UTF_8.INSTANCE, options);3674}36753676/**3677* Write a {@linkplain java.lang.CharSequence CharSequence} to a file.3678* Characters are encoded into bytes using the specified3679* {@linkplain java.nio.charset.Charset charset}.3680*3681* <p> All characters are written as they are, including the line separators in3682* the char sequence. No extra characters are added.3683*3684* <p> The {@code options} parameter specifies how the file is created3685* or opened. If no options are present then this method works as if the3686* {@link StandardOpenOption#CREATE CREATE}, {@link3687* StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link3688* StandardOpenOption#WRITE WRITE} options are present. In other words, it3689* opens the file for writing, creating the file if it doesn't exist, or3690* initially truncating an existing {@link #isRegularFile regular-file} to3691* a size of {@code 0}.3692*3693*3694* @param path3695* the path to the file3696* @param csq3697* the CharSequence to be written3698* @param cs3699* the charset to use for encoding3700* @param options3701* options specifying how the file is opened3702*3703* @return the path3704*3705* @throws IllegalArgumentException3706* if {@code options} contains an invalid combination of options3707* @throws IOException3708* if an I/O error occurs writing to or creating the file, or the3709* text cannot be encoded using the specified charset3710* @throws UnsupportedOperationException3711* if an unsupported option is specified3712* @throws SecurityException3713* In the case of the default provider, and a security manager is3714* installed, the {@link SecurityManager#checkWrite(String) checkWrite}3715* method is invoked to check write access to the file. The {@link3716* SecurityManager#checkDelete(String) checkDelete} method is3717* invoked to check delete access if the file is opened with the3718* {@code DELETE_ON_CLOSE} option.3719*3720* @since 113721*/3722public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)3723throws IOException3724{3725// ensure the text is not null before opening file3726Objects.requireNonNull(path);3727Objects.requireNonNull(csq);3728Objects.requireNonNull(cs);37293730byte[] bytes = JLA.getBytesNoRepl(String.valueOf(csq), cs);3731if (path.getClass().getModule() != Object.class.getModule())3732bytes = bytes.clone();3733write(path, bytes, options);37343735return path;3736}37373738// -- Stream APIs --37393740/**3741* Return a lazily populated {@code Stream}, the elements of3742* which are the entries in the directory. The listing is not recursive.3743*3744* <p> The elements of the stream are {@link Path} objects that are3745* obtained as if by {@link Path#resolve(Path) resolving} the name of the3746* directory entry against {@code dir}. Some file systems maintain special3747* links to the directory itself and the directory's parent directory.3748* Entries representing these links are not included.3749*3750* <p> The stream is <i>weakly consistent</i>. It is thread safe but does3751* not freeze the directory while iterating, so it may (or may not)3752* reflect updates to the directory that occur after returning from this3753* method.3754*3755* <p> The returned stream contains a reference to an open directory.3756* The directory is closed by closing the stream.3757*3758* <p> Operating on a closed stream behaves as if the end of stream3759* has been reached. Due to read-ahead, one or more elements may be3760* returned after the stream has been closed.3761*3762* <p> If an {@link IOException} is thrown when accessing the directory3763* after this method has returned, it is wrapped in an {@link3764* UncheckedIOException} which will be thrown from the method that caused3765* the access to take place.3766*3767* @apiNote3768* This method must be used within a try-with-resources statement or similar3769* control structure to ensure that the stream's open directory is closed3770* promptly after the stream's operations have completed.3771*3772* @param dir The path to the directory3773*3774* @return The {@code Stream} describing the content of the3775* directory3776*3777* @throws NotDirectoryException3778* if the file could not otherwise be opened because it is not3779* a directory <i>(optional specific exception)</i>3780* @throws IOException3781* if an I/O error occurs when opening the directory3782* @throws SecurityException3783* In the case of the default provider, and a security manager is3784* installed, the {@link SecurityManager#checkRead(String) checkRead}3785* method is invoked to check read access to the directory.3786*3787* @see #newDirectoryStream(Path)3788* @since 1.83789*/3790public static Stream<Path> list(Path dir) throws IOException {3791DirectoryStream<Path> ds = Files.newDirectoryStream(dir);3792try {3793final Iterator<Path> delegate = ds.iterator();37943795// Re-wrap DirectoryIteratorException to UncheckedIOException3796Iterator<Path> iterator = new Iterator<>() {3797@Override3798public boolean hasNext() {3799try {3800return delegate.hasNext();3801} catch (DirectoryIteratorException e) {3802throw new UncheckedIOException(e.getCause());3803}3804}3805@Override3806public Path next() {3807try {3808return delegate.next();3809} catch (DirectoryIteratorException e) {3810throw new UncheckedIOException(e.getCause());3811}3812}3813};38143815Spliterator<Path> spliterator =3816Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);3817return StreamSupport.stream(spliterator, false)3818.onClose(asUncheckedRunnable(ds));3819} catch (Error|RuntimeException e) {3820try {3821ds.close();3822} catch (IOException ex) {3823try {3824e.addSuppressed(ex);3825} catch (Throwable ignore) {}3826}3827throw e;3828}3829}38303831/**3832* Return a {@code Stream} that is lazily populated with {@code3833* Path} by walking the file tree rooted at a given starting file. The3834* file tree is traversed <em>depth-first</em>, the elements in the stream3835* are {@link Path} objects that are obtained as if by {@link3836* Path#resolve(Path) resolving} the relative path against {@code start}.3837*3838* <p> The {@code stream} walks the file tree as elements are consumed.3839* The {@code Stream} returned is guaranteed to have at least one3840* element, the starting file itself. For each file visited, the stream3841* attempts to read its {@link BasicFileAttributes}. If the file is a3842* directory and can be opened successfully, entries in the directory, and3843* their <em>descendants</em> will follow the directory in the stream as3844* they are encountered. When all entries have been visited, then the3845* directory is closed. The file tree walk then continues at the next3846* <em>sibling</em> of the directory.3847*3848* <p> The stream is <i>weakly consistent</i>. It does not freeze the3849* file tree while iterating, so it may (or may not) reflect updates to3850* the file tree that occur after returned from this method.3851*3852* <p> By default, symbolic links are not automatically followed by this3853* method. If the {@code options} parameter contains the {@link3854* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are3855* followed. When following links, and the attributes of the target cannot3856* be read, then this method attempts to get the {@code BasicFileAttributes}3857* of the link.3858*3859* <p> If the {@code options} parameter contains the {@link3860* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then the stream keeps3861* track of directories visited so that cycles can be detected. A cycle3862* arises when there is an entry in a directory that is an ancestor of the3863* directory. Cycle detection is done by recording the {@link3864* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,3865* or if file keys are not available, by invoking the {@link #isSameFile3866* isSameFile} method to test if a directory is the same file as an3867* ancestor. When a cycle is detected it is treated as an I/O error with3868* an instance of {@link FileSystemLoopException}.3869*3870* <p> The {@code maxDepth} parameter is the maximum number of levels of3871* directories to visit. A value of {@code 0} means that only the starting3872* file is visited, unless denied by the security manager. A value of3873* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all3874* levels should be visited.3875*3876* <p> When a security manager is installed and it denies access to a file3877* (or directory), then it is ignored and not included in the stream.3878*3879* <p> The returned stream contains references to one or more open directories.3880* The directories are closed by closing the stream.3881*3882* <p> If an {@link IOException} is thrown when accessing the directory3883* after this method has returned, it is wrapped in an {@link3884* UncheckedIOException} which will be thrown from the method that caused3885* the access to take place.3886*3887* @apiNote3888* This method must be used within a try-with-resources statement or similar3889* control structure to ensure that the stream's open directories are closed3890* promptly after the stream's operations have completed.3891*3892* @param start3893* the starting file3894* @param maxDepth3895* the maximum number of directory levels to visit3896* @param options3897* options to configure the traversal3898*3899* @return the {@link Stream} of {@link Path}3900*3901* @throws IllegalArgumentException3902* if the {@code maxDepth} parameter is negative3903* @throws SecurityException3904* If the security manager denies access to the starting file.3905* In the case of the default provider, the {@link3906* SecurityManager#checkRead(String) checkRead} method is invoked3907* to check read access to the directory.3908* @throws IOException3909* if an I/O error is thrown when accessing the starting file.3910* @since 1.83911*/3912public static Stream<Path> walk(Path start,3913int maxDepth,3914FileVisitOption... options)3915throws IOException3916{3917FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);3918try {3919Spliterator<FileTreeWalker.Event> spliterator =3920Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);3921return StreamSupport.stream(spliterator, false)3922.onClose(iterator::close)3923.map(entry -> entry.file());3924} catch (Error|RuntimeException e) {3925iterator.close();3926throw e;3927}3928}39293930/**3931* Return a {@code Stream} that is lazily populated with {@code3932* Path} by walking the file tree rooted at a given starting file. The3933* file tree is traversed <em>depth-first</em>, the elements in the stream3934* are {@link Path} objects that are obtained as if by {@link3935* Path#resolve(Path) resolving} the relative path against {@code start}.3936*3937* <p> This method works as if invoking it were equivalent to evaluating the3938* expression:3939* <blockquote>{@link3940* walk(Path, int, FileVisitOption...)3941* Files.walk(start, Integer.MAX_VALUE, options)3942* }</blockquote>3943* In other words, it visits all levels of the file tree.3944*3945* <p> The returned stream contains references to one or more open directories.3946* The directories are closed by closing the stream.3947*3948* @apiNote3949* This method must be used within a try-with-resources statement or similar3950* control structure to ensure that the stream's open directories are closed3951* promptly after the stream's operations have completed.3952*3953* @param start3954* the starting file3955* @param options3956* options to configure the traversal3957*3958* @return the {@link Stream} of {@link Path}3959*3960* @throws SecurityException3961* If the security manager denies access to the starting file.3962* In the case of the default provider, the {@link3963* SecurityManager#checkRead(String) checkRead} method is invoked3964* to check read access to the directory.3965* @throws IOException3966* if an I/O error is thrown when accessing the starting file.3967*3968* @see #walk(Path, int, FileVisitOption...)3969* @since 1.83970*/3971public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException {3972return walk(start, Integer.MAX_VALUE, options);3973}39743975/**3976* Return a {@code Stream} that is lazily populated with {@code3977* Path} by searching for files in a file tree rooted at a given starting3978* file.3979*3980* <p> This method walks the file tree in exactly the manner specified by3981* the {@link #walk walk} method. For each file encountered, the given3982* {@link BiPredicate} is invoked with its {@link Path} and {@link3983* BasicFileAttributes}. The {@code Path} object is obtained as if by3984* {@link Path#resolve(Path) resolving} the relative path against {@code3985* start} and is only included in the returned {@link Stream} if3986* the {@code BiPredicate} returns true. Compare to calling {@link3987* java.util.stream.Stream#filter filter} on the {@code Stream}3988* returned by {@code walk} method, this method may be more efficient by3989* avoiding redundant retrieval of the {@code BasicFileAttributes}.3990*3991* <p> The returned stream contains references to one or more open directories.3992* The directories are closed by closing the stream.3993*3994* <p> If an {@link IOException} is thrown when accessing the directory3995* after returned from this method, it is wrapped in an {@link3996* UncheckedIOException} which will be thrown from the method that caused3997* the access to take place.3998*3999* @apiNote4000* This method must be used within a try-with-resources statement or similar4001* control structure to ensure that the stream's open directories are closed4002* promptly after the stream's operations have completed.4003*4004* @param start4005* the starting file4006* @param maxDepth4007* the maximum number of directory levels to search4008* @param matcher4009* the function used to decide whether a file should be included4010* in the returned stream4011* @param options4012* options to configure the traversal4013*4014* @return the {@link Stream} of {@link Path}4015*4016* @throws IllegalArgumentException4017* if the {@code maxDepth} parameter is negative4018* @throws SecurityException4019* If the security manager denies access to the starting file.4020* In the case of the default provider, the {@link4021* SecurityManager#checkRead(String) checkRead} method is invoked4022* to check read access to the directory.4023* @throws IOException4024* if an I/O error is thrown when accessing the starting file.4025*4026* @see #walk(Path, int, FileVisitOption...)4027* @since 1.84028*/4029public static Stream<Path> find(Path start,4030int maxDepth,4031BiPredicate<Path, BasicFileAttributes> matcher,4032FileVisitOption... options)4033throws IOException4034{4035FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);4036try {4037Spliterator<FileTreeWalker.Event> spliterator =4038Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);4039return StreamSupport.stream(spliterator, false)4040.onClose(iterator::close)4041.filter(entry -> matcher.test(entry.file(), entry.attributes()))4042.map(entry -> entry.file());4043} catch (Error|RuntimeException e) {4044iterator.close();4045throw e;4046}4047}404840494050/**4051* Read all lines from a file as a {@code Stream}. Unlike {@link4052* #readAllLines(Path, Charset) readAllLines}, this method does not read4053* all lines into a {@code List}, but instead populates lazily as the stream4054* is consumed.4055*4056* <p> Bytes from the file are decoded into characters using the specified4057* charset and the same line terminators as specified by {@code4058* readAllLines} are supported.4059*4060* <p> The returned stream contains a reference to an open file. The file4061* is closed by closing the stream.4062*4063* <p> The file contents should not be modified during the execution of the4064* terminal stream operation. Otherwise, the result of the terminal stream4065* operation is undefined.4066*4067* <p> After this method returns, then any subsequent I/O exception that4068* occurs while reading from the file or when a malformed or unmappable byte4069* sequence is read, is wrapped in an {@link UncheckedIOException} that will4070* be thrown from the4071* {@link java.util.stream.Stream} method that caused the read to take4072* place. In case an {@code IOException} is thrown when closing the file,4073* it is also wrapped as an {@code UncheckedIOException}.4074*4075* @apiNote4076* This method must be used within a try-with-resources statement or similar4077* control structure to ensure that the stream's open file is closed promptly4078* after the stream's operations have completed.4079*4080* @implNote4081* This implementation supports good parallel stream performance for the4082* standard charsets {@link StandardCharsets#UTF_8 UTF-8},4083* {@link StandardCharsets#US_ASCII US-ASCII} and4084* {@link StandardCharsets#ISO_8859_1 ISO-8859-1}. Such4085* <em>line-optimal</em> charsets have the property that the encoded bytes4086* of a line feed ('\n') or a carriage return ('\r') are efficiently4087* identifiable from other encoded characters when randomly accessing the4088* bytes of the file.4089*4090* <p> For non-<em>line-optimal</em> charsets the stream source's4091* spliterator has poor splitting properties, similar to that of a4092* spliterator associated with an iterator or that associated with a stream4093* returned from {@link BufferedReader#lines()}. Poor splitting properties4094* can result in poor parallel stream performance.4095*4096* <p> For <em>line-optimal</em> charsets the stream source's spliterator4097* has good splitting properties, assuming the file contains a regular4098* sequence of lines. Good splitting properties can result in good parallel4099* stream performance. The spliterator for a <em>line-optimal</em> charset4100* takes advantage of the charset properties (a line feed or a carriage4101* return being efficient identifiable) such that when splitting it can4102* approximately divide the number of covered lines in half.4103*4104* @param path4105* the path to the file4106* @param cs4107* the charset to use for decoding4108*4109* @return the lines from the file as a {@code Stream}4110*4111* @throws IOException4112* if an I/O error occurs opening the file4113* @throws SecurityException4114* In the case of the default provider, and a security manager is4115* installed, the {@link SecurityManager#checkRead(String) checkRead}4116* method is invoked to check read access to the file.4117*4118* @see #readAllLines(Path, Charset)4119* @see #newBufferedReader(Path, Charset)4120* @see java.io.BufferedReader#lines()4121* @since 1.84122*/4123public static Stream<String> lines(Path path, Charset cs) throws IOException {4124// Use the good splitting spliterator if:4125// 1) the path is associated with the default file system;4126// 2) the character set is supported; and4127// 3) the file size is such that all bytes can be indexed by int values4128// (this limitation is imposed by ByteBuffer)4129if (path.getFileSystem() == FileSystems.getDefault() &&4130FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) {4131FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);41324133Stream<String> fcls = createFileChannelLinesStream(fc, cs);4134if (fcls != null) {4135return fcls;4136}4137fc.close();4138}41394140return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs));4141}41424143private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException {4144try {4145// Obtaining the size from the FileChannel is much faster4146// than obtaining using path.toFile().length()4147long length = fc.size();4148// FileChannel.size() may in certain circumstances return zero4149// for a non-zero length file so disallow this case.4150if (length > 0 && length <= Integer.MAX_VALUE) {4151FileChannelLinesSpliterator fcls =4152new FileChannelLinesSpliterator(fc, cs, 0, (int) length);4153return StreamSupport.stream(fcls, false)4154.onClose(Files.asUncheckedRunnable(fc))4155.onClose(() -> fcls.close());4156}4157} catch (Error|RuntimeException|IOException e) {4158try {4159fc.close();4160} catch (IOException ex) {4161try {4162e.addSuppressed(ex);4163} catch (Throwable ignore) {4164}4165}4166throw e;4167}4168return null;4169}41704171private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) {4172try {4173return br.lines().onClose(asUncheckedRunnable(br));4174} catch (Error|RuntimeException e) {4175try {4176br.close();4177} catch (IOException ex) {4178try {4179e.addSuppressed(ex);4180} catch (Throwable ignore) {4181}4182}4183throw e;4184}4185}41864187/**4188* Read all lines from a file as a {@code Stream}. Bytes from the file are4189* decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8}4190* {@link Charset charset}.4191*4192* <p> The returned stream contains a reference to an open file. The file4193* is closed by closing the stream.4194*4195* <p> The file contents should not be modified during the execution of the4196* terminal stream operation. Otherwise, the result of the terminal stream4197* operation is undefined.4198*4199* <p> This method works as if invoking it were equivalent to evaluating the4200* expression:4201* <blockquote>{@link4202* lines(Path, Charset)4203* Files.lines(path, StandardCharsets.UTF_8)4204* }</blockquote>4205*4206* @apiNote4207* This method must be used within a try-with-resources statement or similar4208* control structure to ensure that the stream's open file is closed promptly4209* after the stream's operations have completed.4210*4211* @param path4212* the path to the file4213*4214* @return the lines from the file as a {@code Stream}4215*4216* @throws IOException4217* if an I/O error occurs opening the file4218* @throws SecurityException4219* In the case of the default provider, and a security manager is4220* installed, the {@link SecurityManager#checkRead(String) checkRead}4221* method is invoked to check read access to the file.4222*4223* @since 1.84224*/4225public static Stream<String> lines(Path path) throws IOException {4226return lines(path, UTF_8.INSTANCE);4227}4228}422942304231