/* * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions.
*/
/** * This class consists exclusively of static methods that operate on files, * directories, or other types of files. * * <p> In most cases, the methods defined here will delegate to the associated * file system provider to perform the file operations. * * @since 1.7
*/
publicfinalclass Files { // buffer size used for reading and writing privatestaticfinalint BUFFER_SIZE = 8192;
private Files() { }
/** * Returns the {@code FileSystemProvider} to delegate to.
*/ privatestatic FileSystemProvider provider(Path path) { return path.getFileSystem().provider();
}
/** * Convert a Closeable to a Runnable by converting checked IOException * to UncheckedIOException
*/ privatestatic Runnable asUncheckedRunnable(Closeable c) { return () -> { try {
c.close();
} catch (IOException e) { thrownew UncheckedIOException(e);
}
};
}
// -- File contents --
/** * Opens a file, returning an input stream to read from the file. The stream * will not be buffered, and is not required to support the {@link * InputStream#mark mark} or {@link InputStream#reset reset} methods. The * stream will be safe for access by multiple concurrent threads. Reading * commences at the beginning of the file. Whether the returned stream is * <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly * file system provider specific and therefore not specified. * * <p> The {@code options} parameter determines how the file is opened. * If no options are present then it is equivalent to opening the file with * the {@link StandardOpenOption#READ READ} option. In addition to the {@code * READ} option, an implementation may also support additional implementation * specific options. * * @param path * the path to the file to open * @param options * options specifying how the file is opened * * @return a new input stream * * @throws IllegalArgumentException * if an invalid combination of options is specified * @throws UnsupportedOperationException * if an unsupported option is specified * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the file.
*/ publicstatic InputStream newInputStream(Path path, OpenOption... options) throws IOException
{ return provider(path).newInputStream(path, options);
}
/** * Opens or creates a file, returning an output stream that may be used to * write bytes to the file. The resulting stream will not be buffered. The * stream will be safe for access by multiple concurrent threads. Whether * the returned stream is <i>asynchronously closeable</i> and/or * <i>interruptible</i> is highly file system provider specific and * therefore not specified. * * <p> This method opens or creates a file in exactly the manner specified * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} * method with the exception that the {@link StandardOpenOption#READ READ} * option may not be present in the array of options. If no options are * present then this method works as if the {@link StandardOpenOption#CREATE * CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, * and {@link StandardOpenOption#WRITE WRITE} options are present. In other * words, it opens the file for writing, creating the file if it doesn't * exist, or initially truncating an existing {@link #isRegularFile * regular-file} to a size of {@code 0} if it exists. * * <p> <b>Usage Examples:</b> * <pre> * Path path = ... * * // truncate and overwrite an existing file, or create the file if * // it doesn't initially exist * OutputStream out = Files.newOutputStream(path); * * // append to an existing file, fail if the file does not exist * out = Files.newOutputStream(path, APPEND); * * // append to an existing file, create file if it doesn't initially exist * out = Files.newOutputStream(path, CREATE, APPEND); * * // always create new file, failing if it already exists * out = Files.newOutputStream(path, CREATE_NEW); * </pre> * * @param path * the path to the file to open or create * @param options * options specifying how the file is opened * * @return a new output stream * * @throws IllegalArgumentException * if {@code options} contains an invalid combination of options * @throws UnsupportedOperationException * if an unsupported option is specified * @throws FileAlreadyExistsException * If a file of that name already exists and the {@link * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified * <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access to the file. The {@link * SecurityManager#checkDelete(String) checkDelete} method is * invoked to check delete access if the file is opened with the * {@code DELETE_ON_CLOSE} option.
*/ publicstatic OutputStream newOutputStream(Path path, OpenOption... options) throws IOException
{ return provider(path).newOutputStream(path, options);
}
/** * Opens or creates a file, returning a seekable byte channel to access the * file. * * <p> The {@code options} parameter determines how the file is opened. * The {@link StandardOpenOption#READ READ} and {@link * StandardOpenOption#WRITE WRITE} options determine if the file should be * opened for reading and/or writing. If neither option (or the {@link * StandardOpenOption#APPEND APPEND} option) is present then the file is * opened for reading. By default reading or writing commence at the * beginning of the file. * * <p> In the addition to {@code READ} and {@code WRITE}, the following * options may be present: * * <table class="striped"> * <caption style="display:none">Options</caption> * <thead> * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> * </thead> * <tbody> * <tr> * <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th> * <td> If this option is present then the file is opened for writing and * each invocation of the channel's {@code write} method first advances * the position to the end of the file and then writes the requested * data. Whether the advancement of the position and the writing of the * data are done in a single atomic operation is system-dependent and * therefore unspecified. This option may not be used in conjunction * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> * </tr> * <tr> * <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th> * <td> If this option is present then the existing file is truncated to * a size of 0 bytes. This option is ignored when the file is opened only * for reading. </td> * </tr> * <tr> * <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th> * <td> If this option is present then a new file is created, failing if * the file already exists or is a symbolic link. When creating a file the * check for the existence of the file and the creation of the file if it * does not exist is atomic with respect to other file system operations. * This option is ignored when the file is opened only for reading. </td> * </tr> * <tr> * <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th> * <td> If this option is present then an existing file is opened if it * exists, otherwise a new file is created. This option is ignored if the * {@code CREATE_NEW} option is also present or the file is opened only * for reading. </td> * </tr> * <tr> * <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th> * <td> When this option is present then the implementation makes a * <em>best effort</em> attempt to delete the file when closed by the * {@link SeekableByteChannel#close close} method. If the {@code close} * method is not invoked then a <em>best effort</em> attempt is made to * delete the file when the Java virtual machine terminates. </td> * </tr> * <tr> * <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th> * <td> When creating a new file this option is a <em>hint</em> that the * new file will be sparse. This option is ignored when not creating * a new file. </td> * </tr> * <tr> * <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th> * <td> Requires that every update to the file's content or metadata be * written synchronously to the underlying storage device. (see <a * href="package-summary.html#integrity"> Synchronized I/O file * integrity</a>). </td> * </tr> * <tr> * <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th> * <td> Requires that every update to the file's content be written * synchronously to the underlying storage device. (see <a * href="package-summary.html#integrity"> Synchronized I/O file * integrity</a>). </td> * </tr> * </tbody> * </table> * * <p> An implementation may also support additional implementation specific * options. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when a new file is created. * * <p> In the case of the default provider, the returned seekable byte channel * is a {@link java.nio.channels.FileChannel}. * * <p> <b>Usage Examples:</b> * <pre>{@code * Path path = ... * * // open file for reading * ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ))); * * // open file for writing to the end of an existing file, creating * // the file if it doesn't already exist * WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND)); * * // create file with initial permissions, opening it for both reading and writing * FileAttribute<Set<PosixFilePermission>> perms = ... * SeekableByteChannel sbc = * Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms); * }</pre> * * @param path * the path to the file to open or create * @param options * options specifying how the file is opened * @param attrs * an optional list of file attributes to set atomically when * creating the file * * @return a new seekable byte channel * * @throws IllegalArgumentException * if the set contains an invalid combination of options * @throws UnsupportedOperationException * if an unsupported open option is specified or the array contains * attributes that cannot be set atomically when creating the file * @throws FileAlreadyExistsException * If a file of that name already exists and the {@link * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified * and the file is being opened for writing <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the path if the file is * opened for reading. The {@link SecurityManager#checkWrite(String) * checkWrite} method is invoked to check write access to the path * if the file is opened for writing. The {@link * SecurityManager#checkDelete(String) checkDelete} method is * invoked to check delete access if the file is opened with the * {@code DELETE_ON_CLOSE} option. * * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[])
*/ publicstatic SeekableByteChannel newByteChannel(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs) throws IOException
{ return provider(path).newByteChannel(path, options, attrs);
}
/** * Opens or creates a file, returning a seekable byte channel to access the * file. * * <p> This method opens or creates a file in exactly the manner specified * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} * method. * * @param path * the path to the file to open or create * @param options * options specifying how the file is opened * * @return a new seekable byte channel * * @throws IllegalArgumentException * if the set contains an invalid combination of options * @throws UnsupportedOperationException * if an unsupported open option is specified * @throws FileAlreadyExistsException * If a file of that name already exists and the {@link * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified * and the file is being opened for writing <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the path if the file is * opened for reading. The {@link SecurityManager#checkWrite(String) * checkWrite} method is invoked to check write access to the path * if the file is opened for writing. The {@link * SecurityManager#checkDelete(String) checkDelete} method is * invoked to check delete access if the file is opened with the * {@code DELETE_ON_CLOSE} option. * * @see java.nio.channels.FileChannel#open(Path,OpenOption[])
*/ publicstatic SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException
{
Set<OpenOption> set; if (options.length == 0) {
set = Collections.emptySet();
} else {
set = new HashSet<>();
Collections.addAll(set, options);
} return newByteChannel(path, set);
}
staticfinal AcceptAllFilter FILTER = new AcceptAllFilter();
}
/** * Opens a directory, returning a {@link DirectoryStream} to iterate over * all entries in the directory. The elements returned by the directory * stream's {@link DirectoryStream#iterator iterator} are of type {@code * Path}, each one representing an entry in the directory. The {@code Path} * objects are obtained as if by {@link Path#resolve(Path) resolving} the * name of the directory entry against {@code dir}. * * <p> When not using the try-with-resources construct, then directory * stream's {@code close} method should be invoked after iteration is * completed so as to free any resources held for the open directory. * * <p> When an implementation supports operations on entries in the * directory that execute in a race-free manner then the returned directory * stream is a {@link SecureDirectoryStream}. * * @param dir * the path to the directory * * @return a new and open {@code DirectoryStream} object * * @throws NotDirectoryException * if the file could not otherwise be opened because it is not * a directory <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the directory.
*/ publicstatic DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException
{ return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER);
}
/** * Opens a directory, returning a {@link DirectoryStream} to iterate over * the entries in the directory. The elements returned by the directory * stream's {@link DirectoryStream#iterator iterator} are of type {@code * Path}, each one representing an entry in the directory. The {@code Path} * objects are obtained as if by {@link Path#resolve(Path) resolving} the * name of the directory entry against {@code dir}. The entries returned by * the iterator are filtered by matching the {@code String} representation * of their file names against the given <em>globbing</em> pattern. * * <p> For example, suppose we want to iterate over the files ending with * ".java" in a directory: * <pre> * Path dir = ... * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) { * : * } * </pre> * * <p> The globbing pattern is specified by the {@link * FileSystem#getPathMatcher getPathMatcher} method. * * <p> When not using the try-with-resources construct, then directory * stream's {@code close} method should be invoked after iteration is * completed so as to free any resources held for the open directory. * * <p> When an implementation supports operations on entries in the * directory that execute in a race-free manner then the returned directory * stream is a {@link SecureDirectoryStream}. * * @param dir * the path to the directory * @param glob * the glob pattern * * @return a new and open {@code DirectoryStream} object * * @throws java.util.regex.PatternSyntaxException * if the pattern is invalid * @throws NotDirectoryException * if the file could not otherwise be opened because it is not * a directory <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the directory.
*/ publicstatic DirectoryStream<Path> newDirectoryStream(Path dir, String glob) throws IOException
{ // avoid creating a matcher if all entries are required. if (glob.equals("*")) return newDirectoryStream(dir);
// create a matcher and return a filter that uses it.
FileSystem fs = dir.getFileSystem(); final PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<>() {
@Override publicboolean accept(Path entry) { return matcher.matches(entry.getFileName());
}
}; return fs.provider().newDirectoryStream(dir, filter);
}
/** * Opens a directory, returning a {@link DirectoryStream} to iterate over * the entries in the directory. The elements returned by the directory * stream's {@link DirectoryStream#iterator iterator} are of type {@code * Path}, each one representing an entry in the directory. The {@code Path} * objects are obtained as if by {@link Path#resolve(Path) resolving} the * name of the directory entry against {@code dir}. The entries returned by * the iterator are filtered by the given {@link DirectoryStream.Filter * filter}. * * <p> When not using the try-with-resources construct, then directory * stream's {@code close} method should be invoked after iteration is * completed so as to free any resources held for the open directory. * * <p> Where the filter terminates due to an uncaught error or runtime * exception then it is propagated to the {@link Iterator#hasNext() * hasNext} or {@link Iterator#next() next} method. Where an {@code * IOException} is thrown, it results in the {@code hasNext} or {@code * next} method throwing a {@link DirectoryIteratorException} with the * {@code IOException} as the cause. * * <p> When an implementation supports operations on entries in the * directory that execute in a race-free manner then the returned directory * stream is a {@link SecureDirectoryStream}. * * <p> <b>Usage Example:</b> * Suppose we want to iterate over the files in a directory that are * larger than 8K. * <pre> * DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { * public boolean accept(Path file) throws IOException { * return (Files.size(file) > 8192L); * } * }; * Path dir = ... * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) { * : * } * </pre> * * @param dir * the path to the directory * @param filter * the directory stream filter * * @return a new and open {@code DirectoryStream} object * * @throws NotDirectoryException * if the file could not otherwise be opened because it is not * a directory <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the directory.
*/ publicstatic DirectoryStream<Path> newDirectoryStream(Path dir,
DirectoryStream.Filter<? super Path> filter) throws IOException
{ return provider(dir).newDirectoryStream(dir, filter);
}
/** * Creates a new and empty file, failing if the file already exists. The * check for the existence of the file and the creation of the new file if * it does not exist are a single operation that is atomic with respect to * all other filesystem activities that might affect the directory. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when creating the file. Each attribute * is identified by its {@link FileAttribute#name name}. If more than one * attribute of the same name is included in the array then all but the last * occurrence is ignored. * * @param path * the path to the file to create * @param attrs * an optional list of file attributes to set atomically when * creating the file * * @return the file * * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the file * @throws FileAlreadyExistsException * If a file of that name already exists * <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs or the parent directory does not exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access to the new file.
*/ publicstatic Path createFile(Path path, FileAttribute<?>... attrs) throws IOException
{
newByteChannel(path, DEFAULT_CREATE_OPTIONS, attrs).close(); return path;
}
/** * Creates a new directory. The check for the existence of the file and the * creation of the directory if it does not exist are a single operation * that is atomic with respect to all other filesystem activities that might * affect the directory. The {@link #createDirectories createDirectories} * method should be used where it is required to create all nonexistent * parent directories first. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when creating the directory. Each * attribute is identified by its {@link FileAttribute#name name}. If more * than one attribute of the same name is included in the array then all but * the last occurrence is ignored. * * @param dir * the directory to create * @param attrs * an optional list of file attributes to set atomically when * creating the directory * * @return the directory * * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws FileAlreadyExistsException * if a directory could not otherwise be created because a file of * that name already exists <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs or the parent directory does not exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access to the new directory.
*/ publicstatic Path createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException
{
provider(dir).createDirectory(dir, attrs); return dir;
}
/** * Creates a directory by creating all nonexistent parent directories first. * Unlike the {@link #createDirectory createDirectory} method, an exception * is not thrown if the directory could not be created because it already * exists. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when creating the nonexistent * directories. Each file attribute is identified by its {@link * FileAttribute#name name}. If more than one attribute of the same name is * included in the array then all but the last occurrence is ignored. * * <p> If this method fails, then it may do so after creating some, but not * all, of the parent directories. * * @param dir * the directory to create * * @param attrs * an optional list of file attributes to set atomically when * creating the directory * * @return the directory * * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws FileAlreadyExistsException * if {@code dir} exists but is not a directory <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * in the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked prior to attempting to create a directory and * its {@link SecurityManager#checkRead(String) checkRead} is * invoked for each parent directory that is checked. If {@code * dir} is not an absolute path then its {@link Path#toAbsolutePath * toAbsolutePath} may need to be invoked to get its absolute path. * This may invoke the security manager's {@link * SecurityManager#checkPropertyAccess(String) checkPropertyAccess} * method to check access to the system property {@code user.dir}
*/ publicstatic Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
{ // attempt to create the directory try {
createAndCheckIsDirectory(dir, attrs); return dir;
} catch (FileAlreadyExistsException x) { // file exists and is not a directory throw x;
} catch (IOException x) { // parent may not exist or other reason
}
SecurityException se = null; try {
dir = dir.toAbsolutePath();
} catch (SecurityException x) { // don't have permission to get absolute path
se = x;
} // find a descendant that exists
Path parent = dir.getParent(); while (parent != null) { try {
provider(parent).checkAccess(parent); break;
} catch (NoSuchFileException x) { // does not exist
}
parent = parent.getParent();
} if (parent == null) { // unable to find existing parent if (se == null) { thrownew FileSystemException(dir.toString(), null, "Unable to determine if root directory exists");
} else { throw se;
}
}
/** * Used by createDirectories to attempt to create a directory. A no-op * if the directory already exists.
*/ privatestaticvoid createAndCheckIsDirectory(Path dir,
FileAttribute<?>... attrs) throws IOException
{ try {
createDirectory(dir, attrs);
} catch (FileAlreadyExistsException x) { if (!isDirectory(dir)) throw x;
}
}
/** * Creates a new empty file in the specified directory, using the given * prefix and suffix strings to generate its name. The resulting * {@code Path} is associated with the same {@code FileSystem} as the given * directory. * * <p> The details as to how the name of the file is constructed is * implementation dependent and therefore not specified. Where possible * the {@code prefix} and {@code suffix} are used to construct candidate * names in the same manner as the {@link * java.io.File#createTempFile(String,String,File)} method. * * <p> As with the {@code File.createTempFile} methods, this method is only * part of a temporary-file facility. Where used as a <em>work file</em>, * the resulting file may be opened using the {@link * StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the * file is deleted when the appropriate {@code close} method is invoked. * Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the * {@link java.io.File#deleteOnExit} mechanism may be used to delete the * file automatically. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when creating the file. Each attribute * is identified by its {@link FileAttribute#name name}. If more than one * attribute of the same name is included in the array then all but the last * occurrence is ignored. When no file attributes are specified, then the * resulting file may have more restrictive access permissions to files * created by the {@link java.io.File#createTempFile(String,String,File)} * method. * * @param dir * the path to directory in which to create the file * @param prefix * the prefix string to be used in generating the file's name; * may be {@code null} * @param suffix * the suffix string to be used in generating the file's name; * may be {@code null}, in which case "{@code .tmp}" is used * @param attrs * an optional list of file attributes to set atomically when * creating the file * * @return the path to the newly created file that did not exist before * this method was invoked * * @throws IllegalArgumentException * if the prefix or suffix parameters cannot be used to generate * a candidate file name * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws IOException * if an I/O error occurs or {@code dir} does not exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access to the file.
*/ publicstatic Path createTempFile(Path dir,
String prefix,
String suffix,
FileAttribute<?>... attrs) throws IOException
{ return TempFileHelper.createTempFile(Objects.requireNonNull(dir),
prefix, suffix, attrs);
}
/** * Creates an empty file in the default temporary-file directory, using * the given prefix and suffix to generate its name. The resulting {@code * Path} is associated with the default {@code FileSystem}. * * <p> This method works in exactly the manner specified by the * {@link #createTempFile(Path,String,String,FileAttribute[])} method for * the case that the {@code dir} parameter is the temporary-file directory. * * @param prefix * the prefix string to be used in generating the file's name; * may be {@code null} * @param suffix * the suffix string to be used in generating the file's name; * may be {@code null}, in which case "{@code .tmp}" is used * @param attrs * an optional list of file attributes to set atomically when * creating the file * * @return the path to the newly created file that did not exist before * this method was invoked * * @throws IllegalArgumentException * if the prefix or suffix parameters cannot be used to generate * a candidate file name * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws IOException * if an I/O error occurs or the temporary-file directory does not * exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access to the file.
*/ publicstatic Path createTempFile(String prefix,
String suffix,
FileAttribute<?>... attrs) throws IOException
{ return TempFileHelper.createTempFile(null, prefix, suffix, attrs);
}
/** * Creates a new directory in the specified directory, using the given * prefix to generate its name. The resulting {@code Path} is associated * with the same {@code FileSystem} as the given directory. * * <p> The details as to how the name of the directory is constructed is * implementation dependent and therefore not specified. Where possible * the {@code prefix} is used to construct candidate names. * * <p> As with the {@code createTempFile} methods, this method is only * part of a temporary-file facility. A {@link Runtime#addShutdownHook * shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be * used to delete the directory automatically. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * file-attributes} to set atomically when creating the directory. Each * attribute is identified by its {@link FileAttribute#name name}. If more * than one attribute of the same name is included in the array then all but * the last occurrence is ignored. * * @param dir * the path to directory in which to create the directory * @param prefix * the prefix string to be used in generating the directory's name; * may be {@code null} * @param attrs * an optional list of file attributes to set atomically when * creating the directory * * @return the path to the newly created directory that did not exist before * this method was invoked * * @throws IllegalArgumentException * if the prefix cannot be used to generate a candidate directory name * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws IOException * if an I/O error occurs or {@code dir} does not exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access when creating the * directory.
*/ publicstatic Path createTempDirectory(Path dir,
String prefix,
FileAttribute<?>... attrs) throws IOException
{ return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir),
prefix, attrs);
}
/** * Creates a new directory in the default temporary-file directory, using * the given prefix to generate its name. The resulting {@code Path} is * associated with the default {@code FileSystem}. * * <p> This method works in exactly the manner specified by {@link * #createTempDirectory(Path,String,FileAttribute[])} method for the case * that the {@code dir} parameter is the temporary-file directory. * * @param prefix * the prefix string to be used in generating the directory's name; * may be {@code null} * @param attrs * an optional list of file attributes to set atomically when * creating the directory * * @return the path to the newly created directory that did not exist before * this method was invoked * * @throws IllegalArgumentException * if the prefix cannot be used to generate a candidate directory name * @throws UnsupportedOperationException * if the array contains an attribute that cannot be set atomically * when creating the directory * @throws IOException * if an I/O error occurs or the temporary-file directory does not * exist * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkWrite(String) checkWrite} * method is invoked to check write access when creating the * directory.
*/ publicstatic Path createTempDirectory(String prefix,
FileAttribute<?>... attrs) throws IOException
{ return TempFileHelper.createTempDirectory(null, prefix, attrs);
}
/** * Creates a symbolic link to a target <i>(optional operation)</i>. * * <p> The {@code target} parameter is the target of the link. It may be an * {@link Path#isAbsolute absolute} or relative path and may not exist. When * the target is a relative path then file system operations on the resulting * link are relative to the path of the link. * * <p> The {@code attrs} parameter is optional {@link FileAttribute * attributes} to set atomically when creating the link. Each attribute is * identified by its {@link FileAttribute#name name}. If more than one attribute * of the same name is included in the array then all but the last occurrence * is ignored. * * <p> Where symbolic links are supported, but the underlying {@link FileStore} * does not support symbolic links, then this may fail with an {@link * IOException}. Additionally, some operating systems may require that the * Java virtual machine be started with implementation specific privileges to * create symbolic links, in which case this method may throw {@code IOException}. * * @param link * the path of the symbolic link to create * @param target * the target of the symbolic link * @param attrs * the array of attributes to set atomically when creating the * symbolic link * * @return the path to the symbolic link * * @throws UnsupportedOperationException * if the implementation does not support symbolic links or the * array contains an attribute that cannot be set atomically when * creating the symbolic link * @throws FileAlreadyExistsException * if a file with the name already exists <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager * is installed, it denies {@link LinkPermission}{@code ("symbolic")} * or its {@link SecurityManager#checkWrite(String) checkWrite} * method denies write access to the path of the symbolic link.
*/ publicstatic Path createSymbolicLink(Path link, Path target,
FileAttribute<?>... attrs) throws IOException
{
provider(link).createSymbolicLink(link, target, attrs); return link;
}
/** * Creates a new link (directory entry) for an existing file <i>(optional * operation)</i>. * * <p> The {@code link} parameter locates the directory entry to create. * The {@code existing} parameter is the path to an existing file. This * method creates a new directory entry for the file so that it can be * accessed using {@code link} as the path. On some file systems this is * known as creating a "hard link". Whether the file attributes are * maintained for the file or for each directory entry is file system * specific and therefore not specified. Typically, a file system requires * that all links (directory entries) for a file be on the same file system. * Furthermore, on some platforms, the Java virtual machine may require to * be started with implementation specific privileges to create hard links * or to create links to directories. * * @param link * the link (directory entry) to create * @param existing * a path to an existing file * * @return the path to the link (directory entry) * * @throws UnsupportedOperationException * if the implementation does not support adding an existing file * to a directory * @throws FileAlreadyExistsException * if the entry could not otherwise be created because a file of * that name already exists <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager * is installed, it denies {@link LinkPermission}{@code ("hard")} * or its {@link SecurityManager#checkWrite(String) checkWrite} * method denies write access to either the link or the * existing file.
*/ publicstatic Path createLink(Path link, Path existing) throws IOException {
provider(link).createLink(link, existing); return link;
}
/** * Deletes a file. * * <p> An implementation may require to examine the file to determine if the * file is a directory. Consequently this method may not be atomic with respect * to other file system operations. If the file is a symbolic link then the * symbolic link itself, not the final target of the link, is deleted. * * <p> If the file is a directory then the directory must be empty. In some * implementations a directory has entries for special files or links that * are created when the directory is created. In such implementations a * directory is considered empty when only the special entries exist. * This method can be used with the {@link #walkFileTree walkFileTree} * method to delete a directory and all entries in the directory, or an * entire <i>file-tree</i> where required. * * <p> On some operating systems it may not be possible to remove a file when * it is open and in use by this Java virtual machine or other programs. * * @param path * the path to the file to delete * * @throws NoSuchFileException * if the file does not exist <i>(optional specific exception)</i> * @throws DirectoryNotEmptyException * if the file is a directory and could not otherwise be deleted * because the directory is not empty <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkDelete(String)} method * is invoked to check delete access to the file
*/ publicstaticvoiddelete(Path path) throws IOException {
provider(path).delete(path);
}
/** * Deletes a file if it exists. * * <p> As with the {@link #delete(Path) delete(Path)} method, an * implementation may need to examine the file to determine if the file is a * directory. Consequently this method may not be atomic with respect to * other file system operations. If the file is a symbolic link, then the * symbolic link itself, not the final target of the link, is deleted. * * <p> If the file is a directory then the directory must be empty. In some * implementations a directory has entries for special files or links that * are created when the directory is created. In such implementations a * directory is considered empty when only the special entries exist. * * <p> On some operating systems it may not be possible to remove a file when * it is open and in use by this Java virtual machine or other programs. * * @param path * the path to the file to delete * * @return {@code true} if the file was deleted by this method; {@code * false} if the file could not be deleted because it did not * exist * * @throws DirectoryNotEmptyException * if the file is a directory and could not otherwise be deleted * because the directory is not empty <i>(optional specific * exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkDelete(String)} method * is invoked to check delete access to the file.
*/ publicstaticboolean deleteIfExists(Path path) throws IOException { return provider(path).deleteIfExists(path);
}
// -- Copying and moving files --
/** * Copy a file to a target file. * * <p> This method copies a file to the target file with the {@code * options} parameter specifying how the copy is performed. By default, the * copy fails if the target file already exists or is a symbolic link, * except if the source and target are the {@link #isSameFile same} file, in * which case the method completes without copying the file. File attributes * are not required to be copied to the target file. If symbolic links are * supported, and the file is a symbolic link, then the final target of the * link is copied. If the file is a directory then an empty directory is * created in the target location (entries in the directory are not * copied). This method can be used with the {@link #walkFileTree * walkFileTree} method to copy a directory and all entries in the directory, * or an entire <i>file-tree</i> where required. * * <p> The {@code options} parameter may include any of the following: * * <table class="striped"> * <caption style="display:none">Options</caption> * <thead> * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> * </thead> * <tbody> * <tr> * <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th> * <td> Replace an existing file. A non-empty directory cannot be * replaced. If the target file exists and is a symbolic link, then the * symbolic link itself, not the target of the link, is replaced. </td> * </tr> * <tr> * <th scope="row"> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </th> * <td> Attempts to copy the file attributes associated with this file to * the target file. The exact file attributes that are copied is platform * and file system dependent and therefore unspecified. Minimally, the * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is * copied to the target file if supported by both the source and target * file stores. Copying of file timestamps may result in precision * loss. </td> * </tr> * <tr> * <th scope="row"> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </th> * <td> Symbolic links are not followed. If the file is a symbolic link, * then the symbolic link itself, not the target of the link, is copied. * It is implementation specific if file attributes can be copied to the * new link. In other words, the {@code COPY_ATTRIBUTES} option may be * ignored when copying a symbolic link. </td> * </tr> * </tbody> * </table> * * <p> An implementation of this interface may support additional * implementation specific options. * * <p> Copying a file is not an atomic operation. If an {@link IOException} * is thrown, then it is possible that the target file is incomplete or some * of its file attributes have not been copied from the source file. When * the {@code REPLACE_EXISTING} option is specified and the target file * exists, then the target file is replaced. The check for the existence of * the file and the creation of the new file may not be atomic with respect * to other file system activities. * * <p> <b>Usage Example:</b> * Suppose we want to copy a file into a directory, giving it the same file * name as the source file: * <pre> * Path source = ... * Path newdir = ... * Files.copy(source, newdir.resolve(source.getFileName()); * </pre> * * @param source * the path to the file to copy * @param target * the path to the target file (may be associated with a different * provider to the source path) * @param options * options specifying how the copy should be done * * @return the path to the target file * * @throws UnsupportedOperationException * if the array contains a copy option that is not supported * @throws FileAlreadyExistsException * if the target file exists but cannot be replaced because the * {@code REPLACE_EXISTING} option is not specified <i>(optional * specific exception)</i> * @throws DirectoryNotEmptyException * the {@code REPLACE_EXISTING} option is specified but the file * cannot be replaced because it is a non-empty directory * <i>(optional specific exception)</i> * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the source file, the * {@link SecurityManager#checkWrite(String) checkWrite} is invoked * to check write access to the target file. If a symbolic link is * copied the security manager is invoked to check {@link * LinkPermission}{@code ("symbolic")}.
*/ publicstatic Path copy(Path source, Path target, CopyOption... options) throws IOException
{
FileSystemProvider provider = provider(source); if (provider(target) == provider) { // same provider
provider.copy(source, target, options);
} else { // different providers
CopyMoveHelper.copyToForeignTarget(source, target, options);
} return target;
}
/** * Move or rename a file to a target file. * * <p> By default, this method attempts to move the file to the target * file, failing if the target file exists except if the source and * target are the {@link #isSameFile same} file, in which case this method * has no effect. If the file is a symbolic link then the symbolic link * itself, not the target of the link, is moved. This method may be * invoked to move an empty directory. In some implementations a directory * has entries for special files or links that are created when the * directory is created. In such implementations a directory is considered * empty when only the special entries exist. When invoked to move a * directory that is not empty then the directory is moved if it does not * require moving the entries in the directory. For example, renaming a * directory on the same {@link FileStore} will usually not require moving * the entries in the directory. When moving a directory requires that its * entries be moved then this method fails (by throwing an {@code * IOException}). To move a <i>file tree</i> may involve copying rather * than moving directories and this can be done using the {@link * #copy copy} method in conjunction with the {@link * #walkFileTree Files.walkFileTree} utility method. * * <p> The {@code options} parameter may include any of the following: * * <table class="striped"> * <caption style="display:none">Options</caption> * <thead> * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> * </thead> * <tbody> * <tr> * <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th> * <td> Replace an existing file. A non-empty directory cannot be * replaced. If the target file exists and is a symbolic link, then the * symbolic link itself, not the target of the link, is replaced. </td> * </tr> * <tr> * <th scope="row"> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </th> * <td> The move is performed as an atomic file system operation and all * other options are ignored. If the target file exists then it is * implementation specific if the existing file is replaced or this method * fails by throwing an {@link IOException}. If the move cannot be * performed as an atomic file system operation then {@link * AtomicMoveNotSupportedException} is thrown. This can arise, for * example, when the target location is on a different {@code FileStore} * and would require that the file be copied, or target location is * associated with a different provider to this object. </td> * </tbody> * </table> * * <p> An implementation of this interface may support additional * implementation specific options. * * <p> Moving a file will copy the {@link * BasicFileAttributes#lastModifiedTime last-modified-time} to the target * file if supported by both source and target file stores. Copying of file * timestamps may result in precision loss. An implementation may also * attempt to copy other file attributes but is not required to fail if the * file attributes cannot be copied. When the move is performed as * a non-atomic operation, and an {@code IOException} is thrown, then the * state of the files is not defined. The original file and the target file * may both exist, the target file may be incomplete or some of its file * attributes may not been copied from the original file. * * <p> <b>Usage Examples:</b> * Suppose we want to rename a file to "newname", keeping the file in the * same directory: * <pre> * Path source = ... * Files.move(source, source.resolveSibling("newname")); * </pre> * Alternatively, suppose we want to move a file to new directory, keeping * the same file name, and replacing any existing file of that name in the * directory: * <pre> * Path source = ... * Path newdir = ... * Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING); * </pre> * * @param source * the path to the file to move * @param target * the path to the target file (may be associated with a different * provider to the source path) * @param options * options specifying how the move should be done * * @return the path to the target file * * @throws UnsupportedOperationException * if the array contains a copy option that is not supported * @throws FileAlreadyExistsException * if the target file exists but cannot be replaced because the * {@code REPLACE_EXISTING} option is not specified <i>(optional * specific exception)</i> * @throws DirectoryNotEmptyException * the {@code REPLACE_EXISTING} option is specified but the file * cannot be replaced because it is a non-empty directory, or the * source is a non-empty directory containing entries that would * be required to be moved <i>(optional specific exceptions)</i> * @throws AtomicMoveNotSupportedException * if the options array contains the {@code ATOMIC_MOVE} option but * the file cannot be moved as an atomic file system operation. * @throws IOException * if an I/O error occurs * @throws SecurityException * In the case of the default provider, and a security manager is
--> --------------------
--> maximum size reached
--> --------------------
Messung V0.5
¤ Dauer der Verarbeitung: 0.10 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.