public final classFilesextendsObject
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
| Modifier and Type | Method | Description |
|---|---|---|
static long | copy(InputStream in,Path target,CopyOption... options) | Copies all bytes from an input stream to a file. |
static long | copy(Path source,OutputStream out) | Copies all bytes from a file to an output stream. |
staticPath | copy(Path source,Path target,CopyOption... options) | Copy a file to a target file. |
staticPath | createDirectories(Path dir,FileAttribute<?>... attrs) | Creates a directory by creating all nonexistent parent directories first. |
staticPath | createDirectory(Path dir,FileAttribute<?>... attrs) | Creates a new directory. |
staticPath | createFile(Path path,FileAttribute<?>... attrs) | Creates a new and empty file, failing if the file already exists. |
staticPath | createLink(Path link,Path existing) | Creates a new link (directory entry) for an existing file(optional operation). |
staticPath | createSymbolicLink(Path link,Path target,FileAttribute<?>... attrs) | Creates a symbolic link to a target(optional operation). |
staticPath | createTempDirectory(Path dir,String prefix,FileAttribute<?>... attrs) | Creates a new directory in the specified directory, using the given prefix to generate its name. |
staticPath | createTempDirectory(String prefix,FileAttribute<?>... attrs) | Creates a new directory in the default temporary-file directory, using the given prefix to generate its name. |
staticPath | createTempFile(Path dir,String prefix,String suffix,FileAttribute<?>... attrs) | Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. |
staticPath | createTempFile(String prefix,String suffix,FileAttribute<?>... attrs) | Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. |
static void | delete(Path path) | Deletes a file. |
static boolean | deleteIfExists(Path path) | Deletes a file if it exists. |
static boolean | exists(Path path,LinkOption... options) | Tests whether a file exists. |
staticStream<Path> | find(Path start, int maxDepth,BiPredicate<Path,BasicFileAttributes> matcher,FileVisitOption... options) | Return a Stream that is lazily populated withPath by searching for files in a file tree rooted at a given starting file. |
staticObject | getAttribute(Path path,String attribute,LinkOption... options) | Reads the value of a file attribute. |
static <V extendsFileAttributeView> | getFileAttributeView(Path path,Class<V> type,LinkOption... options) | Returns a file attribute view of a given type. |
staticFileStore | getFileStore(Path path) | Returns the FileStore representing the file store where a file is located. |
staticFileTime | getLastModifiedTime(Path path,LinkOption... options) | Returns a file's last modified time. |
staticUserPrincipal | getOwner(Path path,LinkOption... options) | Returns the owner of a file. |
staticSet<PosixFilePermission> | getPosixFilePermissions(Path path,LinkOption... options) | Returns a file's POSIX file permissions. |
static boolean | isDirectory(Path path,LinkOption... options) | Tests whether a file is a directory. |
static boolean | isExecutable(Path path) | Tests whether a file is executable. |
static boolean | isHidden(Path path) | Tells whether or not a file is consideredhidden. |
static boolean | isReadable(Path path) | Tests whether a file is readable. |
static boolean | isRegularFile(Path path,LinkOption... options) | Tests whether a file is a regular file with opaque content. |
static boolean | isSameFile(Path path,Path path2) | Tests if two paths locate the same file. |
static boolean | isSymbolicLink(Path path) | Tests whether a file is a symbolic link. |
static boolean | isWritable(Path path) | Tests whether a file is writable. |
staticStream<String> | lines(Path path) | Read all lines from a file as a Stream. |
staticStream<String> | lines(Path path,Charset cs) | Read all lines from a file as a Stream. |
staticStream<Path> | list(Path dir) | Return a lazily populated Stream, the elements of which are the entries in the directory. |
staticPath | move(Path source,Path target,CopyOption... options) | Move or rename a file to a target file. |
staticBufferedReader | newBufferedReader(Path path) | Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner. |
staticBufferedReader | newBufferedReader(Path path,Charset cs) | Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner. |
staticBufferedWriter | newBufferedWriter(Path path,Charset cs,OpenOption... options) | Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. |
staticBufferedWriter | newBufferedWriter(Path path,OpenOption... options) | Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. |
staticSeekableByteChannel | newByteChannel(Path path,OpenOption... options) | Opens or creates a file, returning a seekable byte channel to access the file. |
staticSeekableByteChannel | newByteChannel(Path path,Set<? extendsOpenOption> options,FileAttribute<?>... attrs) | Opens or creates a file, returning a seekable byte channel to access the file. |
staticDirectoryStream<Path> | newDirectoryStream(Path dir) | Opens a directory, returning a DirectoryStream to iterate over all entries in the directory. |
staticDirectoryStream<Path> | newDirectoryStream(Path dir,DirectoryStream.Filter<? superPath> filter) | Opens a directory, returning a DirectoryStream to iterate over the entries in the directory. |
staticDirectoryStream<Path> | newDirectoryStream(Path dir,String glob) | Opens a directory, returning a DirectoryStream to iterate over the entries in the directory. |
staticInputStream | newInputStream(Path path,OpenOption... options) | Opens a file, returning an input stream to read from the file. |
staticOutputStream | newOutputStream(Path path,OpenOption... options) | Opens or creates a file, returning an output stream that may be used to write bytes to the file. |
static boolean | notExists(Path path,LinkOption... options) | Tests whether the file located by this path does not exist. |
staticString | probeContentType(Path path) | Probes the content type of a file. |
static byte[] | readAllBytes(Path path) | Reads all the bytes from a file. |
staticList<String> | readAllLines(Path path) | Read all lines from a file. |
staticList<String> | readAllLines(Path path,Charset cs) | Read all lines from a file. |
static <A extendsBasicFileAttributes> | readAttributes(Path path,Class<A> type,LinkOption... options) | Reads a file's attributes as a bulk operation. |
staticMap<String,Object> | readAttributes(Path path,String attributes,LinkOption... options) | Reads a set of file attributes as a bulk operation. |
staticPath | readSymbolicLink(Path link) | Reads the target of a symbolic link(optional operation). |
staticPath | setAttribute(Path path,String attribute,Object value,LinkOption... options) | Sets the value of a file attribute. |
staticPath | setLastModifiedTime(Path path,FileTime time) | Updates a file's last modified time attribute. |
staticPath | setOwner(Path path,UserPrincipal owner) | Updates the file owner. |
staticPath | setPosixFilePermissions(Path path,Set<PosixFilePermission> perms) | Sets a file's POSIX permissions. |
static long | size(Path path) | Returns the size of a file (in bytes). |
staticStream<Path> | walk(Path start,FileVisitOption... options) | Return a Stream that is lazily populated withPath by walking the file tree rooted at a given starting file. |
staticStream<Path> | walk(Path start, int maxDepth,FileVisitOption... options) | Return a Stream that is lazily populated withPath by walking the file tree rooted at a given starting file. |
staticPath | walkFileTree(Path start,FileVisitor<? superPath> visitor) | Walks a file tree. |
staticPath | walkFileTree(Path start,Set<FileVisitOption> options, int maxDepth,FileVisitor<? superPath> visitor) | Walks a file tree. |
staticPath | write(Path path, byte[] bytes,OpenOption... options) | Writes bytes to a file. |
staticPath | write(Path path,Iterable<? extendsCharSequence> lines,Charset cs,OpenOption... options) | Write lines of text to a file. |
staticPath | write(Path path,Iterable<? extendsCharSequence> lines,OpenOption... options) | Write lines of text to a file. |
public static InputStream newInputStream(Path path,OpenOption... options) throwsIOException
mark orreset methods. The stream will be safe for access by multiple concurrent threads. Reading commences at the beginning of the file. Whether the returned stream isasynchronously closeable and/orinterruptible is highly file system provider specific and therefore not specified. Theoptions parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with theREAD option. In addition to theREAD option, an implementation may also support additional implementation specific options.
path - the path to the file to openoptions - options specifying how the file is openedIllegalArgumentException - if an invalid combination of options is specifiedUnsupportedOperationException - if an unsupported option is specifiedIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static OutputStream newOutputStream(Path path,OpenOption... options) throwsIOException
This method opens or creates a file in exactly the manner specified by thenewByteChannel method with the exception that theREAD option may not be present in the array of options. If no options are present then this method works as if theCREATE,TRUNCATE_EXISTING, andWRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existingregular-file to a size of0 if it exists.
Usage Examples:
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);
path - the path to the file to open or createoptions - options specifying how the file is openedIllegalArgumentException - ifoptions contains an invalid combination of optionsUnsupportedOperationException - if an unsupported option is specifiedIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file. ThecheckDelete method is invoked to check delete access if the file is opened with theDELETE_ON_CLOSE option.public static SeekableByteChannel newByteChannel(Path path,Set<? extendsOpenOption> options,FileAttribute<?>... attrs) throwsIOException
Theoptions parameter determines how the file is opened. TheREAD andWRITE options determine if the file should be opened for reading and/or writing. If neither option (or theAPPEND option) is present then the file is opened for reading. By default reading or writing commence at the beginning of the file.
In the addition toREAD andWRITE, the following options may be present:
| Option | Description |
|---|---|
APPEND | If this option is present then the file is opened for writing and each invocation of the channel'swrite 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 theREAD orTRUNCATE_EXISTING options. |
TRUNCATE_EXISTING | 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. |
CREATE_NEW | 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. |
CREATE | 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 theCREATE_NEW option is also present or the file is opened only for reading. |
DELETE_ON_CLOSE | When this option is present then the implementation makes abest effort attempt to delete the file when closed by theclose method. If theclose method is not invoked then abest effort attempt is made to delete the file when the Java virtual machine terminates. |
SPARSE | When creating a new file this option is ahint that the new file will be sparse. This option is ignored when not creating a new file. |
SYNC | Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. (see Synchronized I/O file integrity). |
DSYNC | Requires that every update to the file's content be written synchronously to the underlying storage device. (see Synchronized I/O file integrity). |
An implementation may also support additional implementation specific options.
Theattrs parameter is optionalfile-attributes to set atomically when a new file is created.
In the case of the default provider, the returned seekable byte channel is aFileChannel.
Usage Examples:
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);path - the path to the file to open or createoptions - options specifying how the file is openedattrs - an optional list of file attributes to set atomically when creating the fileIllegalArgumentException - if the set contains an invalid combination of optionsUnsupportedOperationException - if an unsupported open option is specified or the array contains attributes that cannot be set atomically when creating the fileFileAlreadyExistsException - if a file of that name already exists and theCREATE_NEW option is specified(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the path if the file is opened for reading. ThecheckWrite method is invoked to check write access to the path if the file is opened for writing. ThecheckDelete method is invoked to check delete access if the file is opened with theDELETE_ON_CLOSE option.FileChannel.open(Path,Set,FileAttribute[])public static SeekableByteChannel newByteChannel(Path path,OpenOption... options) throwsIOException
This method opens or creates a file in exactly the manner specified by thenewByteChannel method.
path - the path to the file to open or createoptions - options specifying how the file is openedIllegalArgumentException - if the set contains an invalid combination of optionsUnsupportedOperationException - if an unsupported open option is specifiedFileAlreadyExistsException - if a file of that name already exists and theCREATE_NEW option is specified(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the path if the file is opened for reading. ThecheckWrite method is invoked to check write access to the path if the file is opened for writing. ThecheckDelete method is invoked to check delete access if the file is opened with theDELETE_ON_CLOSE option.FileChannel.open(Path,OpenOption[])public static DirectoryStream<Path> newDirectoryStream(Path dir) throwsIOException
DirectoryStream to iterate over all entries in the directory. The elements returned by the directory stream'siterator are of typePath, each one representing an entry in the directory. ThePath objects are obtained as if byresolving the name of the directory entry againstdir. When not using the try-with-resources construct, then directory stream'sclose method should be invoked after iteration is completed so as to free any resources held for the open directory.
When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is aSecureDirectoryStream.
dir - the path to the directoryDirectoryStream objectNotDirectoryException - if the file could not otherwise be opened because it is not a directory(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the directory.public static DirectoryStream<Path> newDirectoryStream(Path dir,String glob) throwsIOException
DirectoryStream to iterate over the entries in the directory. The elements returned by the directory stream'siterator are of typePath, each one representing an entry in the directory. ThePath objects are obtained as if byresolving the name of the directory entry againstdir. The entries returned by the iterator are filtered by matching theString representation of their file names against the givenglobbing pattern.For example, suppose we want to iterate over the files ending with ".java" in a directory:
Path dir = ... try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) { : } The globbing pattern is specified by thegetPathMatcher method.
When not using the try-with-resources construct, then directory stream'sclose method should be invoked after iteration is completed so as to free any resources held for the open directory.
When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is aSecureDirectoryStream.
dir - the path to the directoryglob - the glob patternDirectoryStream objectPatternSyntaxException - if the pattern is invalidNotDirectoryException - if the file could not otherwise be opened because it is not a directory(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the directory.public static DirectoryStream<Path> newDirectoryStream(Path dir,DirectoryStream.Filter<? superPath> filter) throwsIOException
DirectoryStream to iterate over the entries in the directory. The elements returned by the directory stream'siterator are of typePath, each one representing an entry in the directory. ThePath objects are obtained as if byresolving the name of the directory entry againstdir. The entries returned by the iterator are filtered by the givenfilter. When not using the try-with-resources construct, then directory stream'sclose method should be invoked after iteration is completed so as to free any resources held for the open directory.
Where the filter terminates due to an uncaught error or runtime exception then it is propagated to thehasNext ornext method. Where anIOException is thrown, it results in thehasNext ornext method throwing aDirectoryIteratorException with theIOException as the cause.
When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is aSecureDirectoryStream.
Usage Example: Suppose we want to iterate over the files in a directory that are larger than 8K.
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)) { : }dir - the path to the directoryfilter - the directory stream filterDirectoryStream objectNotDirectoryException - if the file could not otherwise be opened because it is not a directory(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the directory.public static Path createFile(Path path,FileAttribute<?>... attrs) throwsIOException
Theattrs parameter is optionalfile-attributes to set atomically when creating the file. Each attribute is identified by itsname. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
path - the path to the file to createattrs - an optional list of file attributes to set atomically when creating the fileUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the fileFileAlreadyExistsException - if a file of that name already exists(optional specific exception)IOException - if an I/O error occurs or the parent directory does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the new file.public static Path createDirectory(Path dir,FileAttribute<?>... attrs) throwsIOException
createDirectories method should be used where it is required to create all nonexistent parent directories first. Theattrs parameter is optionalfile-attributes to set atomically when creating the directory. Each attribute is identified by itsname. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
dir - the directory to createattrs - an optional list of file attributes to set atomically when creating the directoryUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryFileAlreadyExistsException - if a directory could not otherwise be created because a file of that name already exists(optional specific exception)IOException - if an I/O error occurs or the parent directory does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the new directory.public static Path createDirectories(Path dir,FileAttribute<?>... attrs) throwsIOException
createDirectory method, an exception is not thrown if the directory could not be created because it already exists. Theattrs parameter is optionalfile-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by itsname. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
dir - the directory to createattrs - an optional list of file attributes to set atomically when creating the directoryUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryFileAlreadyExistsException - ifdir exists but is not a directory(optional specific exception)IOException - if an I/O error occursSecurityException - in the case of the default provider, and a security manager is installed, thecheckWrite method is invoked prior to attempting to create a directory and itscheckRead is invoked for each parent directory that is checked. Ifdir is not an absolute path then itstoAbsolutePath may need to be invoked to get its absolute path. This may invoke the security manager'scheckPropertyAccess method to check access to the system propertyuser.dirpublic static Path createTempFile(Path dir,String prefix,String suffix,FileAttribute<?>... attrs) throwsIOException
Path is associated with the sameFileSystem as the given directory. The details as to how the name of the file is constructed is implementation dependent and therefore not specified. Where possible theprefix andsuffix are used to construct candidate names in the same manner as theFile.createTempFile(String,String,File) method.
As with theFile.createTempFile methods, this method is only part of a temporary-file facility. Where used as awork files, the resulting file may be opened using theDELETE_ON_CLOSE option so that the file is deleted when the appropriateclose method is invoked. Alternatively, ashutdown-hook, or theFile.deleteOnExit() mechanism may be used to delete the file automatically.
Theattrs parameter is optionalfile-attributes to set atomically when creating the file. Each attribute is identified by itsname. 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 theFile.createTempFile(String,String,File) method.
dir - the path to directory in which to create the fileprefix - the prefix string to be used in generating the file's name; may benullsuffix - the suffix string to be used in generating the file's name; may benull, in which case ".tmp" is usedattrs - an optional list of file attributes to set atomically when creating the fileIllegalArgumentException - if the prefix or suffix parameters cannot be used to generate a candidate file nameUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryIOException - if an I/O error occurs ordir does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static Path createTempFile(String prefix,String suffix,FileAttribute<?>... attrs) throwsIOException
Path is associated with the defaultFileSystem. This method works in exactly the manner specified by thecreateTempFile(Path,String,String,FileAttribute[]) method for the case that thedir parameter is the temporary-file directory.
prefix - the prefix string to be used in generating the file's name; may benullsuffix - the suffix string to be used in generating the file's name; may benull, in which case ".tmp" is usedattrs - an optional list of file attributes to set atomically when creating the fileIllegalArgumentException - if the prefix or suffix parameters cannot be used to generate a candidate file nameUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryIOException - if an I/O error occurs or the temporary-file directory does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static Path createTempDirectory(Path dir,String prefix,FileAttribute<?>... attrs) throwsIOException
Path is associated with the sameFileSystem as the given directory. The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible theprefix is used to construct candidate names.
As with thecreateTempFile methods, this method is only part of a temporary-file facility. Ashutdown-hook, or theFile.deleteOnExit() mechanism may be used to delete the directory automatically.
Theattrs parameter is optionalfile-attributes to set atomically when creating the directory. Each attribute is identified by itsname. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
dir - the path to directory in which to create the directoryprefix - the prefix string to be used in generating the directory's name; may benullattrs - an optional list of file attributes to set atomically when creating the directoryIllegalArgumentException - if the prefix cannot be used to generate a candidate directory nameUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryIOException - if an I/O error occurs ordir does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access when creating the directory.public static Path createTempDirectory(String prefix,FileAttribute<?>... attrs) throwsIOException
Path is associated with the defaultFileSystem. This method works in exactly the manner specified bycreateTempDirectory(Path,String,FileAttribute[]) method for the case that thedir parameter is the temporary-file directory.
prefix - the prefix string to be used in generating the directory's name; may benullattrs - an optional list of file attributes to set atomically when creating the directoryIllegalArgumentException - if the prefix cannot be used to generate a candidate directory nameUnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directoryIOException - if an I/O error occurs or the temporary-file directory does not existSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access when creating the directory.public static Path createSymbolicLink(Path link,Path target,FileAttribute<?>... attrs) throwsIOException
Thetarget parameter is the target of the link. It may be anabsolute 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.
Theattrs parameter is optionalattributes to set atomically when creating the link. Each attribute is identified by itsname. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
Where symbolic links are supported, but the underlyingFileStore does not support symbolic links, then this may fail with anIOException. 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 throwIOException.
link - the path of the symbolic link to createtarget - the target of the symbolic linkattrs - the array of attributes to set atomically when creating the symbolic linkUnsupportedOperationException - if the implementation does not support symbolic links or the array contains an attribute that cannot be set atomically when creating the symbolic linkFileAlreadyExistsException - if a file with the name already exists(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it deniesLinkPermission("symbolic") or itscheckWrite method denies write access to the path of the symbolic link.public static Path createLink(Path link,Path existing) throwsIOException
Thelink parameter locates the directory entry to create. Theexisting parameter is the path to an existing file. This method creates a new directory entry for the file so that it can be accessed usinglink 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.
link - the link (directory entry) to createexisting - a path to an existing fileUnsupportedOperationException - if the implementation does not support adding an existing file to a directoryFileAlreadyExistsException - if the entry could not otherwise be created because a file of that name already exists(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it deniesLinkPermission("hard") or itscheckWrite method denies write access to either the link or the existing file.public static void delete(Path path) throwsIOException
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.
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 thewalkFileTree method to delete a directory and all entries in the directory, or an entirefile-tree where required.
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.
path - the path to the file to deleteNoSuchFileException - if the file does not exist(optional specific exception)DirectoryNotEmptyException - if the file is a directory and could not otherwise be deleted because the directory is not empty(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, theSecurityManager.checkDelete(String) method is invoked to check delete access to the filepublic static boolean deleteIfExists(Path path) throwsIOException
As with thedelete(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.
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.
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.
path - the path to the file to deletetrue if the file was deleted by this method;false if the file could not be deleted because it did not existDirectoryNotEmptyException - if the file is a directory and could not otherwise be deleted because the directory is not empty(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, theSecurityManager.checkDelete(String) method is invoked to check delete access to the file.public static Path copy(Path source,Path target,CopyOption... options) throwsIOException
This method copies a file to the target file with theoptions 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 thesame 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 it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with thewalkFileTree method to copy a directory and all entries in the directory, or an entirefile-tree where required.
Theoptions parameter may include any of the following:
| Option | Description |
|---|---|
REPLACE_EXISTING | If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. |
COPY_ATTRIBUTES | 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, thelast-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. |
NOFOLLOW_LINKS | 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, theCOPY_ATTRIBUTES option may be ignored when copying a symbolic link. |
An implementation of this interface may support additional implementation specific options.
Copying a file is not an atomic operation. If anIOException 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 theREPLACE_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.
Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:
Path source = ... Path newdir = ... Files.copy(source, newdir.resolve(source.getFileName());
source - the path to the file to copytarget - the path to the target file (may be associated with a different provider to the source path)options - options specifying how the copy should be doneUnsupportedOperationException - if the array contains a copy option that is not supportedFileAlreadyExistsException - if the target file exists but cannot be replaced because theREPLACE_EXISTING option is not specified(optional specific exception)DirectoryNotEmptyException - theREPLACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the source file, thecheckWrite is invoked to check write access to the target file. If a symbolic link is copied the security manager is invoked to checkLinkPermission("symbolic").public static Path move(Path source,Path target,CopyOption... options) throwsIOException
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 thesame 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 sameFileStore 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 anIOException). To move afile tree may involve copying rather than moving directories and this can be done using thecopy method in conjunction with theFiles.walkFileTree utility method.
Theoptions parameter may include any of the following:
| Option | Description |
|---|---|
REPLACE_EXISTING | If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. |
ATOMIC_MOVE | 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 anIOException. If the move cannot be performed as an atomic file system operation thenAtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a differentFileStore and would require that the file be copied, or target location is associated with a different provider to this object. |
An implementation of this interface may support additional implementation specific options.
Moving a file will copy thelast-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 anIOException 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.
Usage Examples: Suppose we want to rename a file to "newname", keeping the file in the same directory:
Path source = ... Files.move(source, source.resolveSibling("newname")); 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:Path source = ... Path newdir = ... Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
source - the path to the file to movetarget - the path to the target file (may be associated with a different provider to the source path)options - options specifying how the move should be doneUnsupportedOperationException - if the array contains a copy option that is not supportedFileAlreadyExistsException - if the target file exists but cannot be replaced because theREPLACE_EXISTING option is not specified(optional specific exception)DirectoryNotEmptyException - theREPLACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory(optional specific exception)AtomicMoveNotSupportedException - if the options array contains theATOMIC_MOVE option but the file cannot be moved as an atomic file system operation.IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to both the source and target file.public static Path readSymbolicLink(Path link) throwsIOException
If the file system supportssymbolic links then this method is used to read the target of the link, failing if the file is not a symbolic link. The target of the link need not exist. The returnedPath object will be associated with the same file system aslink.
link - the path to the symbolic linkPath object representing the target of the linkUnsupportedOperationException - if the implementation does not support symbolic linksNotLinkException - if the target could otherwise not be read because the file is not a symbolic link(optional specific exception)IOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it checks thatFilePermission has been granted with the "readlink" action to read the link.public static FileStore getFileStore(Path path) throwsIOException
FileStore representing the file store where a file is located. Once a reference to theFileStore is obtained it is implementation specific if operations on the returnedFileStore, orFileStoreAttributeView objects obtained from it, continue to depend on the existence of the file. In particular the behavior is not defined for the case that the file is deleted or moved to a different file store.
path - the path to the fileIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file, and in addition it checksRuntimePermission ("getFileStoreAttributes")public static boolean isSameFile(Path path,Path path2) throwsIOException
If bothPath objects areequal then this method returnstrue without checking if the file exists. If the twoPath objects are associated with different providers then this method returnsfalse. Otherwise, this method checks if bothPath objects locate the same file, and depending on the implementation, may require to open or access both files.
If the file system and files remain static, then this method implements an equivalence relation for non-nullPaths.
Pathf,isSameFile(f,f) should returntrue.Pathsf andg,isSameFile(f,g) will equalisSameFile(g,f).Pathsf,g, andh, ifisSameFile(f,g) returnstrue andisSameFile(g,h) returnstrue, thenisSameFile(f,h) will return returntrue.path - one path to the filepath2 - the other pathtrue if, and only if, the two paths locate the same fileIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to both files.BasicFileAttributes.fileKey()public static boolean isHidden(Path path) throwsIOException
hidden attribute is set.Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.
path - the path to the file to testtrue if the file is considered hiddenIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static String probeContentType(Path path) throwsIOException
This method uses the installedFileTypeDetector implementations to probe the given file to determine its content type. Each file type detector'sprobeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.
A given invocation of the Java virtual machine maintains a system-wide list of file type detectors. Installed file type detectors are loaded using the service-provider loading facility defined by theServiceLoader class. Installed file type detectors are loaded using the system class loader. If the system class loader cannot be found then the extension class loader is used; If the extension class loader cannot be found then the bootstrap class loader is used. File type detectors are typically installed by placing them in a JAR file on the application class path or in the extension directory, the JAR file contains a provider-configuration file namedjava.nio.file.spi.FileTypeDetector in the resource directoryMETA-INF/services, and the file lists one or more fully-qualified names of concrete subclass ofFileTypeDetector that have a zero argument constructor. If the process of locating or instantiating the installed file type detectors fails then an unspecified error is thrown. The ordering that installed providers are located is implementation specific.
The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined byRFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.
path - the path to the file to probenull if the content type cannot be determinedIOException - if an I/O error occursSecurityException - If a security manager is installed and it denies an unspecified permission required by a file type detector implementation.public static <V extendsFileAttributeView> V getFileAttributeView(Path path,Class<V> type,LinkOption... options)
A file attribute view provides a read-only or updatable view of a set of file attributes. This method is intended to be used where the file attribute view defines type-safe methods to read or update the file attributes. Thetype parameter is the type of the attribute view required and the method returns an instance of that type if supported. TheBasicFileAttributeView type supports access to the basic attributes of a file. Invoking this method to select a file attribute view of that type will always return an instance of that class.
Theoptions array may be used to indicate how symbolic links are handled by the resulting file attribute view for the case that the file is a symbolic link. By default, symbolic links are followed. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed. This option is ignored by implementations that do not support symbolic links.
Usage Example: Suppose we want read or set a file's ACL, if supported:
Path path = ... AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); if (view != null) { List<AclEntry> acl = view.getAcl(); : }V - TheFileAttributeView typepath - the path to the filetype - theClass object corresponding to the file attribute viewoptions - options indicating how symbolic links are handlednull if the attribute view type is not availablepublic static <A extendsBasicFileAttributes> A readAttributes(Path path,Class<A> type,LinkOption... options) throwsIOException
Thetype parameter is the type of the attributes required and this method returns an instance of that type if supported. All implementations support a basic set of file attributes and so invoking this method with atype parameter ofBasicFileAttributes.class will not throwUnsupportedOperationException.
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
It is implementation specific if all file attributes are read as an atomic operation with respect to other file system operations.
Usage Example: Suppose we want to read a file's attributes in bulk:
Path path = ... BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);Alternatively, suppose we want to read file's POSIX attributes without following symbolic links:
PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS);
A - TheBasicFileAttributes typepath - the path to the filetype - theClass of the file attributes required to readoptions - options indicating how symbolic links are handledUnsupportedOperationException - if an attributes of the given type are not supportedIOException - if an I/O error occursSecurityException - In the case of the default provider, a security manager is installed, itscheckRead method is invoked to check read access to the file. If this method is invoked to read security sensitive attributes then the security manager may be invoke to check for additional permissions.public static Path setAttribute(Path path,String attribute,Object value,LinkOption... options) throwsIOException
Theattribute parameter identifies the attribute to be set and takes the form:
[view-name:]attribute-namewhere square brackets [...] delineate an optional component and the character
':' stands for itself.view-name is thename of aFileAttributeView that identifies a set of file attributes. If not specified then it defaults to"basic", the name of the file attribute view that identifies the basic set of file attributes common to many file systems.attribute-name is the name of the attribute within the set.
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is set. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we want to set the DOS "hidden" attribute:
Path path = ... Files.setAttribute(path, "dos:hidden", true);
path - the path to the fileattribute - the attribute to setvalue - the attribute valueoptions - options indicating how symbolic links are handledpath parameterUnsupportedOperationException - if the attribute view is not availableIllegalArgumentException - if the attribute name is not specified, or is not recognized, or the attribute value is of the correct type but has an inappropriate valueClassCastException - if the attribute value is not of the expected type or is a collection containing elements that are not of the expected typeIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, itscheckWrite method denies write access to the file. If this method is invoked to set security sensitive attributes then the security manager may be invoked to check for additional permissions.public static Object getAttribute(Path path,String attribute,LinkOption... options) throwsIOException
Theattribute parameter identifies the attribute to be read and takes the form:
[view-name:]attribute-namewhere square brackets [...] delineate an optional component and the character
':' stands for itself.view-name is thename of aFileAttributeView that identifies a set of file attributes. If not specified then it defaults to"basic", the name of the file attribute view that identifies the basic set of file attributes common to many file systems.attribute-name is the name of the attribute.
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we require the user ID of the file owner on a system that supports a "unix" view:
Path path = ... int uid = (Integer)Files.getAttribute(path, "unix:uid");
path - the path to the fileattribute - the attribute to readoptions - options indicating how symbolic links are handledUnsupportedOperationException - if the attribute view is not availableIllegalArgumentException - if the attribute name is not specified or is not recognizedIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file. If this method is invoked to read security sensitive attributes then the security manager may be invoked to check for additional permissions.public static Map<String,Object> readAttributes(Path path,String attributes,LinkOption... options) throwsIOException
Theattributes parameter identifies the attributes to be read and takes the form:
[view-name:]attribute-listwhere square brackets [...] delineate an optional component and the character
':' stands for itself.view-name is thename of aFileAttributeView that identifies a set of file attributes. If not specified then it defaults to"basic", the name of the file attribute view that identifies the basic set of file attributes common to many file systems.
Theattribute-list component is a comma separated list of zero or more names of attributes to read. If the list contains the value"*" then all attributes are read. Attributes that are not supported are ignored and will not be present in the returned map. It is implementation specific if all attributes are read as an atomic operation with respect to other file system operations.
The following examples demonstrate possible values for theattributes parameter:
"*"Read all basic-file-attributes."size,lastModifiedTime,lastAccessTime"Reads the file size, last modified time, and last access time attributes. "posix:*"Read all POSIX-file-attributes."posix:permissions,owner,size"Reads the POSX file permissions, owner, and file size.
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
path - the path to the fileattributes - the attributes to readoptions - options indicating how symbolic links are handledUnsupportedOperationException - if the attribute view is not availableIllegalArgumentException - if no attributes are specified or an unrecognized attributes is specifiedIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file. If this method is invoked to read security sensitive attributes then the security manager may be invoke to check for additional permissions.public static Set<PosixFilePermission> getPosixFilePermissions(Path path,LinkOption... options) throwsIOException
Thepath parameter is associated with aFileSystem that supports thePosixFileAttributeView. This attribute view provides access to file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
path - the path to the fileoptions - options indicating how symbolic links are handledUnsupportedOperationException - if the associated file system does not support thePosixFileAttributeViewIOException - if an I/O error occursSecurityException - In the case of the default provider, a security manager is installed, and it deniesRuntimePermission("accessUserInformation") or itscheckRead method denies read access to the file.public static Path setPosixFilePermissions(Path path,Set<PosixFilePermission> perms) throwsIOException
Thepath parameter is associated with aFileSystem that supports thePosixFileAttributeView. This attribute view provides access to file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
path - The path to the fileperms - The new set of permissionsUnsupportedOperationException - if the associated file system does not support thePosixFileAttributeViewClassCastException - if the sets contains elements that are not of typePosixFilePermissionIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it deniesRuntimePermission("accessUserInformation") or itscheckWrite method denies write access to the file.public static UserPrincipal getOwner(Path path,LinkOption... options) throwsIOException
Thepath parameter is associated with a file system that supportsFileOwnerAttributeView. This file attribute view provides access to a file attribute that is the owner of the file.
path - The path to the fileoptions - options indicating how symbolic links are handledUnsupportedOperationException - if the associated file system does not support theFileOwnerAttributeViewIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it deniesRuntimePermission("accessUserInformation") or itscheckRead method denies read access to the file.public static Path setOwner(Path path,UserPrincipal owner) throwsIOException
Thepath parameter is associated with a file system that supportsFileOwnerAttributeView. This file attribute view provides access to a file attribute that is the owner of the file.
Usage Example: Suppose we want to make "joe" the owner of a file:
Path path = ... UserPrincipalLookupService lookupService = provider(path).getUserPrincipalLookupService(); UserPrincipal joe = lookupService.lookupPrincipalByName("joe"); Files.setOwner(path, joe);path - The path to the fileowner - The new file ownerUnsupportedOperationException - if the associated file system does not support theFileOwnerAttributeViewIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, it deniesRuntimePermission("accessUserInformation") or itscheckWrite method denies write access to the file.FileSystem.getUserPrincipalLookupService(),UserPrincipalLookupServicepublic static boolean isSymbolicLink(Path path)
Where it is required to distinguish an I/O exception from the case that the file is not a symbolic link then the file attributes can be read with thereadAttributes method and the file type tested with theBasicFileAttributes.isSymbolicLink() method.
path - The path to the filetrue if the file is a symbolic link;false if the file does not exist, is not a symbolic link, or it cannot be determined if the file is a symbolic link or not.SecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file.public static boolean isDirectory(Path path,LinkOption... options)
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a directory then the file attributes can be read with thereadAttributes method and the file type tested with theBasicFileAttributes.isDirectory() method.
path - the path to the file to testoptions - options indicating how symbolic links are handledtrue if the file is a directory;false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.SecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file.public static boolean isRegularFile(Path path,LinkOption... options)
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a regular file then the file attributes can be read with thereadAttributes method and the file type tested with theBasicFileAttributes.isRegularFile() method.
path - the path to the fileoptions - options indicating how symbolic links are handledtrue if the file is a regular file;false if the file does not exist, is not a regular file, or it cannot be determined if the file is a regular file or not.SecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file.public static FileTime getLastModifiedTime(Path path,LinkOption... options) throwsIOException
Theoptions array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
path - the path to the fileoptions - options indicating how symbolic links are handledFileTime representing the time the file was last modified, or an implementation specific default when a time stamp to indicate the time of last modification is not supported by the file systemIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file.BasicFileAttributes.lastModifiedTime()public static Path setLastModifiedTime(Path path,FileTime time) throwsIOException
IOException.Usage Example: Suppose we want to set the last modified time to the current time:
Path path = ... FileTime now = FileTime.fromMillis(System.currentTimeMillis()); Files.setLastModifiedTime(path, now);
path - the path to the filetime - the new last modified timeIOException - if an I/O error occursSecurityException - In the case of the default provider, the security manager'scheckWrite method is invoked to check write access to fileBasicFileAttributeView.setTimes(java.nio.file.attribute.FileTime, java.nio.file.attribute.FileTime, java.nio.file.attribute.FileTime)public static long size(Path path) throwsIOException
regular files is implementation specific and therefore unspecified.path - the path to the fileIOException - if an I/O error occursSecurityException - In the case of the default provider, and a security manager is installed, itscheckRead method denies read access to the file.BasicFileAttributes.size()public static boolean exists(Path path,LinkOption... options)
Theoptions parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security sensitive applications.
path - the path to the file to testoptions - options indicating how symbolic links are handled .true if the file exists;false if the file does not exist or its existence cannot be determined.SecurityException - In the case of the default provider, theSecurityManager.checkRead(String) is invoked to check read access to the file.notExists(java.nio.file.Path, java.nio.file.LinkOption...)public static boolean notExists(Path path,LinkOption... options)
Theoptions parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the optionNOFOLLOW_LINKS is present then symbolic links are not followed.
Note that this method is not the complement of theexists method. Where it is not possible to determine if a file exists or not then both methods returnfalse. As with theexists method, the result of this method is immediately outdated. If this method indicates the file does exist then there is no guarantee that a subsequence attempt to create the file will succeed. Care should be taken when using this method in security sensitive applications.
path - the path to the file to testoptions - options indicating how symbolic links are handledtrue if the file does not exist;false if the file exists or its existence cannot be determinedSecurityException - In the case of the default provider, theSecurityManager.checkRead(String) is invoked to check read access to the file.public static boolean isReadable(Path path)
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
path - the path to the file to checktrue if the file exists and is readable;false if the file does not exist, read access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determinedSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead is invoked to check read access to the file.public static boolean isWritable(Path path)
Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
path - the path to the file to checktrue if the file exists and is writable;false if the file does not exist, write access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determinedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite is invoked to check write access to the file.public static boolean isExecutable(Path path)
execute the file. The semantics may differ when checking access to a directory. For example, on UNIX systems, checking for execute access checks that the Java virtual machine has permission to search the directory in order to access file or subdirectories.Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to execute the file will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
path - the path to the file to checktrue if the file exists and is executable;false if the file does not exist, execute access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determinedSecurityException - In the case of the default provider, and a security manager is installed, thecheckExec is invoked to check execute access to the file.public static Path walkFileTree(Path start,Set<FileVisitOption> options, int maxDepth,FileVisitor<? superPath> visitor) throwsIOException
This method walks a file tree rooted at a given starting file. The file tree traversal isdepth-first with the givenFileVisitor invoked for each file encountered. File tree traversal completes when all accessible files in the tree have been visited, or a visit method returns a result ofTERMINATE. Where a visit method terminates due anIOException, an uncaught error, or runtime exception, then the traversal is terminated and the error or exception is propagated to the caller of this method.
For each file encountered this method attempts to read itsBasicFileAttributes. If the file is not a directory then thevisitFile method is invoked with the file attributes. If the file attributes cannot be read, due to an I/O exception, then thevisitFileFailed method is invoked with the I/O exception.
Where the file is a directory, and the directory could not be opened, then thevisitFileFailed method is invoked with the I/O exception, after which, the file tree walk continues, by default, at the nextsibling of the directory.
Where the directory is opened successfully, then the entries in the directory, and theirdescendants are visited. When all entries have been visited, or an I/O error occurs during iteration of the directory, then the directory is closed and the visitor'spostVisitDirectory method is invoked. The file tree walk then continues, by default, at the nextsibling of the directory.
By default, symbolic links are not automatically followed by this method. If theoptions parameter contains theFOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get theBasicFileAttributes of the link. If they can be read then thevisitFile method is invoked with the attributes of the link (otherwise thevisitFileFailed method is invoked as specified above).
If theoptions parameter contains theFOLLOW_LINKS option then this method keeps track of directories visited so that cycles can be detected. A cycle arises when there is an entry in a directory that is an ancestor of the directory. Cycle detection is done by recording thefile-key of directories, or if file keys are not available, by invoking theisSameFile method to test if a directory is the same file as an ancestor. When a cycle is detected it is treated as an I/O error, and thevisitFileFailed method is invoked with an instance ofFileSystemLoopException.
ThemaxDepth parameter is the maximum number of levels of directories to visit. A value of0 means that only the starting file is visited, unless denied by the security manager. A value ofMAX_VALUE may be used to indicate that all levels should be visited. ThevisitFile method is invoked for all files, including directories, encountered atmaxDepth, unless the basic file attributes cannot be read, in which case thevisitFileFailed method is invoked.
If a visitor returns a result ofnull thenNullPointerException is thrown.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and the visitor is not invoked for that file (or directory).
start - the starting fileoptions - options to configure the traversalmaxDepth - the maximum number of directory levels to visitvisitor - the file visitor to invoke for each fileIllegalArgumentException - if themaxDepth parameter is negativeSecurityException - If the security manager denies access to the starting file. In the case of the default provider, thecheckRead method is invoked to check read access to the directory.IOException - if an I/O error is thrown by a visitor methodpublic static Path walkFileTree(Path start,FileVisitor<? superPath> visitor) throwsIOException
This method works as if invoking it were equivalent to evaluating the expression:
In other words, it does not follow symbolic links, and visits all levels of the file tree.walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)
start - the starting filevisitor - the file visitor to invoke for each fileSecurityException - If the security manager denies access to the starting file. In the case of the default provider, thecheckRead method is invoked to check read access to the directory.IOException - if an I/O error is thrown by a visitor methodpublic static BufferedReader newBufferedReader(Path path,Charset cs) throwsIOException
BufferedReader that may be used to read text from the file in an efficient manner. Bytes from the file are decoded into characters using the specified charset. Reading commences at the beginning of the file. TheReader methods that read from the file throwIOException if a malformed or unmappable byte sequence is read.
path - the path to the filecs - the charset to use for decodingIOException - if an I/O error occurs opening the fileSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.readAllLines(java.nio.file.Path, java.nio.charset.Charset)public static BufferedReader newBufferedReader(Path path) throwsIOException
BufferedReader to read text from the file in an efficient manner. Bytes from the file are decoded into characters using theUTF-8charset.This method works as if invoking it were equivalent to evaluating the expression:
Files.newBufferedReader(path, StandardCharsets.UTF_8)path - the path to the fileIOException - if an I/O error occurs opening the fileSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static BufferedWriter newBufferedWriter(Path path,Charset cs,OpenOption... options) throwsIOException
BufferedWriter that may be used to write text to the file in an efficient manner. Theoptions parameter specifies how the the file is created or opened. If no options are present then this method works as if theCREATE,TRUNCATE_EXISTING, andWRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existingregular-file to a size of0 if it exists. TheWriter methods to write text throwIOException if the text cannot be encoded using the specified charset.
path - the path to the filecs - the charset to use for encodingoptions - options specifying how the file is openedIOException - if an I/O error occurs opening or creating the fileUnsupportedOperationException - if an unsupported option is specifiedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.write(Path,Iterable,Charset,OpenOption[])public static BufferedWriter newBufferedWriter(Path path,OpenOption... options) throwsIOException
BufferedWriter to write text to the file in an efficient manner. The text is encoded into bytes for writing using theUTF-8charset.This method works as if invoking it were equivalent to evaluating the expression:
Files.newBufferedWriter(path, StandardCharsets.UTF_8, options)path - the path to the fileoptions - options specifying how the file is openedIOException - if an I/O error occurs opening or creating the fileUnsupportedOperationException - if an unsupported option is specifiedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static long copy(InputStream in,Path target,CopyOption... options) throwsIOException
By default, the copy fails if the target file already exists or is a symbolic link. If theREPLACE_EXISTING option is specified, and the target file already exists, then it is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link is replaced. In this release, theREPLACE_EXISTING option is the only option required to be supported by this method. Additional options may be supported in future releases.
If an I/O error occurs reading from the input stream or writing to the file, then it may do so after the target file has been created and after some bytes have been read or written. Consequently the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.
This method may block indefinitely reading from the input stream (or writing to the file). The behavior for the case that the input stream isasynchronously closed or the thread interrupted during the copy is highly input stream and file system provider specific and therefore not specified.
Usage example: Suppose we want to capture a web page and save it to a file:
Path path = ... URI u = URI.create("http://java.sun.com/"); try (InputStream in = u.toURL().openStream()) { Files.copy(in, path); }in - the input stream to read fromtarget - the path to the fileoptions - options specifying how the copy should be doneIOException - if an I/O error occurs when reading or writingFileAlreadyExistsException - if the target file exists but cannot be replaced because theREPLACE_EXISTING option is not specified(optional specific exception)DirectoryNotEmptyException - theREPLACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory(optional specific exception) *UnsupportedOperationException - ifoptions contains a copy option that is not supportedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file. Where theREPLACE_EXISTING option is specified, the security manager'scheckDelete method is invoked to check that an existing file can be deleted.public static long copy(Path source,OutputStream out) throwsIOException
If an I/O error occurs reading from the file or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the output stream may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.
This method may block indefinitely writing to the output stream (or reading from the file). The behavior for the case that the output stream isasynchronously closed or the thread interrupted during the copy is highly output stream and file system provider specific and therefore not specified.
Note that if the given output stream isFlushable then itsflush method may need to invoked after this method completes so as to flush any buffered output.
source - the path to the fileout - the output stream to write toIOException - if an I/O error occurs when reading or writingSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static byte[] readAllBytes(Path path) throwsIOException
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
path - the path to the fileIOException - if an I/O error occurs reading from the streamOutOfMemoryError - if an array of the required size cannot be allocated, for example the file is larger that2GBSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static List<String> readAllLines(Path path,Charset cs) throwsIOException
This method recognizes the following as line terminators:
\u000D followed by\u000A, CARRIAGE RETURN followed by LINE FEED\u000A, LINE FEED\u000D, CARRIAGE RETURNAdditional Unicode line terminators may be recognized in future releases.
Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.
path - the path to the filecs - the charset to use for decodingList; whether theList is modifiable or not is implementation dependent and therefore not specifiedIOException - if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is readSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.newBufferedReader(java.nio.file.Path, java.nio.charset.Charset)public static List<String> readAllLines(Path path) throwsIOException
UTF-8charset.This method works as if invoking it were equivalent to evaluating the expression:
Files.readAllLines(path, StandardCharsets.UTF_8)path - the path to the fileList; whether theList is modifiable or not is implementation dependent and therefore not specifiedIOException - if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is readSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.public static Path write(Path path, byte[] bytes,OpenOption... options) throwsIOException
options parameter specifies how the the file is created or opened. If no options are present then this method works as if theCREATE,TRUNCATE_EXISTING, andWRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existingregular-file to a size of0. All bytes in the byte array are written to the file. The method ensures that the file is closed when all bytes have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:
Path path = ... byte[] bytes = ... Files.write(path, bytes, StandardOpenOption.APPEND);
path - the path to the filebytes - the byte array with the bytes to writeoptions - options specifying how the file is openedIOException - if an I/O error occurs writing to or creating the fileUnsupportedOperationException - if an unsupported option is specifiedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static Path write(Path path,Iterable<? extendsCharSequence> lines,Charset cs,OpenOption... options) throwsIOException
line.separator. Characters are encoded into bytes using the specified charset. Theoptions parameter specifies how the the file is created or opened. If no options are present then this method works as if theCREATE,TRUNCATE_EXISTING, andWRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existingregular-file to a size of0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.
path - the path to the filelines - an object to iterate over the char sequencescs - the charset to use for encodingoptions - options specifying how the file is openedIOException - if an I/O error occurs writing to or creating the file, or the text cannot be encoded using the specified charsetUnsupportedOperationException - if an unsupported option is specifiedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static Path write(Path path,Iterable<? extendsCharSequence> lines,OpenOption... options) throwsIOException
UTF-8charset.This method works as if invoking it were equivalent to evaluating the expression:
Files.write(path, lines, StandardCharsets.UTF_8, options);path - the path to the filelines - an object to iterate over the char sequencesoptions - options specifying how the file is openedIOException - if an I/O error occurs writing to or creating the file, or the text cannot be encoded asUTF-8UnsupportedOperationException - if an unsupported option is specifiedSecurityException - In the case of the default provider, and a security manager is installed, thecheckWrite method is invoked to check write access to the file.public static Stream<Path> list(Path dir) throwsIOException
Stream, the elements of which are the entries in the directory. The listing is not recursive. The elements of the stream arePath objects that are obtained as if byresolving the name of the directory entry againstdir. Some file systems maintain special links to the directory itself and the directory's parent directory. Entries representing these links are not included.
The stream isweakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after returning from this method.
The returned stream encapsulates aDirectoryStream. If timely disposal of file system resources is required, thetry-with-resources construct should be used to ensure that the stream'sclose method is invoked after the stream operations are completed.
Operating on a closed stream behaves as if the end of stream has been reached. Due to read-ahead, one or more elements may be returned after the stream has been closed.
If anIOException is thrown when accessing the directory after this method has returned, it is wrapped in anUncheckedIOException which will be thrown from the method that caused the access to take place.
dir - The path to the directoryStream describing the content of the directoryNotDirectoryException - if the file could not otherwise be opened because it is not a directory(optional specific exception)IOException - if an I/O error occurs when opening the directorySecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the directory.newDirectoryStream(Path)public static Stream<Path> walk(Path start, int maxDepth,FileVisitOption... options) throwsIOException
Stream that is lazily populated withPath by walking the file tree rooted at a given starting file. The file tree is traverseddepth-first, the elements in the stream arePath objects that are obtained as if byresolving the relative path againststart. Thestream walks the file tree as elements are consumed. TheStream returned is guaranteed to have at least one element, the starting file itself. For each file visited, the stream attempts to read itsBasicFileAttributes. If the file is a directory and can be opened successfully, entries in the directory, and theirdescendants will follow the directory in the stream as they are encountered. When all entries have been visited, then the directory is closed. The file tree walk then continues at the nextsibling of the directory.
The stream isweakly consistent. It does not freeze the file tree while iterating, so it may (or may not) reflect updates to the file tree that occur after returned from this method.
By default, symbolic links are not automatically followed by this method. If theoptions parameter contains theFOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get theBasicFileAttributes of the link.
If theoptions parameter contains theFOLLOW_LINKS option then the stream keeps track of directories visited so that cycles can be detected. A cycle arises when there is an entry in a directory that is an ancestor of the directory. Cycle detection is done by recording thefile-key of directories, or if file keys are not available, by invoking theisSameFile method to test if a directory is the same file as an ancestor. When a cycle is detected it is treated as an I/O error with an instance ofFileSystemLoopException.
ThemaxDepth parameter is the maximum number of levels of directories to visit. A value of0 means that only the starting file is visited, unless denied by the security manager. A value ofMAX_VALUE may be used to indicate that all levels should be visited.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and not included in the stream.
The returned stream encapsulates one or moreDirectoryStreams. If timely disposal of file system resources is required, thetry-with-resources construct should be used to ensure that the stream'sclose method is invoked after the stream operations are completed. Operating on a closed stream will result in anIllegalStateException.
If anIOException is thrown when accessing the directory after this method has returned, it is wrapped in anUncheckedIOException which will be thrown from the method that caused the access to take place.
start - the starting filemaxDepth - the maximum number of directory levels to visitoptions - options to configure the traversalStream ofPathIllegalArgumentException - if themaxDepth parameter is negativeSecurityException - If the security manager denies access to the starting file. In the case of the default provider, thecheckRead method is invoked to check read access to the directory.IOException - if an I/O error is thrown when accessing the starting file.public static Stream<Path> walk(Path start,FileVisitOption... options) throwsIOException
Stream that is lazily populated withPath by walking the file tree rooted at a given starting file. The file tree is traverseddepth-first, the elements in the stream arePath objects that are obtained as if byresolving the relative path againststart.This method works as if invoking it were equivalent to evaluating the expression:
In other words, it visits all levels of the file tree.walk(start, Integer.MAX_VALUE, options)
The returned stream encapsulates one or moreDirectoryStreams. If timely disposal of file system resources is required, thetry-with-resources construct should be used to ensure that the stream'sclose method is invoked after the stream operations are completed. Operating on a closed stream will result in anIllegalStateException.
start - the starting fileoptions - options to configure the traversalStream ofPathSecurityException - If the security manager denies access to the starting file. In the case of the default provider, thecheckRead method is invoked to check read access to the directory.IOException - if an I/O error is thrown when accessing the starting file.walk(Path, int, FileVisitOption...)public static Stream<Path> find(Path start, int maxDepth,BiPredicate<Path,BasicFileAttributes> matcher,FileVisitOption... options) throwsIOException
Stream that is lazily populated withPath by searching for files in a file tree rooted at a given starting file. This method walks the file tree in exactly the manner specified by thewalk method. For each file encountered, the givenBiPredicate is invoked with itsPath andBasicFileAttributes. ThePath object is obtained as if byresolving the relative path againststart and is only included in the returnedStream if theBiPredicate returns true. Compare to callingfilter on theStream returned bywalk method, this method may be more efficient by avoiding redundant retrieval of theBasicFileAttributes.
The returned stream encapsulates one or moreDirectoryStreams. If timely disposal of file system resources is required, thetry-with-resources construct should be used to ensure that the stream'sclose method is invoked after the stream operations are completed. Operating on a closed stream will result in anIllegalStateException.
If anIOException is thrown when accessing the directory after returned from this method, it is wrapped in anUncheckedIOException which will be thrown from the method that caused the access to take place.
start - the starting filemaxDepth - the maximum number of directory levels to searchmatcher - the function used to decide whether a file should be included in the returned streamoptions - options to configure the traversalStream ofPathIllegalArgumentException - if themaxDepth parameter is negativeSecurityException - If the security manager denies access to the starting file. In the case of the default provider, thecheckRead method is invoked to check read access to the directory.IOException - if an I/O error is thrown when accessing the starting file.walk(Path, int, FileVisitOption...)public static Stream<String> lines(Path path,Charset cs) throwsIOException
Stream. UnlikereadAllLines, this method does not read all lines into aList, but instead populates lazily as the stream is consumed. Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified byreadAllLines are supported.
After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in anUncheckedIOException that will be thrown from theStream method that caused the read to take place. In case anIOException is thrown when closing the file, it is also wrapped as anUncheckedIOException.
The returned stream encapsulates aReader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream'sclose method is invoked after the stream operations are completed.
path - the path to the filecs - the charset to use for decodingStreamIOException - if an I/O error occurs opening the fileSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.readAllLines(Path, Charset),newBufferedReader(Path, Charset),BufferedReader.lines()public static Stream<String> lines(Path path) throwsIOException
Stream. Bytes from the file are decoded into characters using theUTF-8charset.This method works as if invoking it were equivalent to evaluating the expression:
Files.lines(path, StandardCharsets.UTF_8)path - the path to the fileStreamIOException - if an I/O error occurs opening the fileSecurityException - In the case of the default provider, and a security manager is installed, thecheckRead method is invoked to check read access to the file.