public final class Files extends Object
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
Modifier and Type | Method and Description |
---|---|
static Path |
copy(Path source,
Path target,
CopyOption... options)
Copy a file to a target file.
|
static Path |
createDirectories(Path dir,
FileAttribute<?>... attrs)
Creates a directory by creating all nonexistent parent directories first.
|
static Path |
createDirectory(Path dir,
FileAttribute<?>... attrs)
Creates a new directory.
|
static Path |
createFile(Path path,
FileAttribute<?>... attrs)
Creates a new and empty file, failing if the file already exists.
|
static Path |
createTempDirectory(Path dir,
String prefix,
FileAttribute<?>... attrs)
Creates a new directory in the specified directory, using the given
prefix to generate its name.
|
static Path |
createTempDirectory(String prefix,
FileAttribute<?>... attrs)
Creates a new directory in the default temporary-file directory, using
the given prefix to generate its name.
|
static Path |
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.
|
static Path |
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.
|
static Object |
getAttribute(Path path,
String attribute,
LinkOption... options)
Reads the value of a file attribute.
|
static FileStore |
getFileStore(Path path)
Returns the
FileStore representing the file store where a file
is located. |
static FileTime |
getLastModifiedTime(Path path,
LinkOption... options)
Returns a file's last modified time.
|
static boolean |
isDirectory(Path path,
LinkOption... options)
Tests whether a file is a directory.
|
static boolean |
isHidden(Path path)
Tells whether or not a file is considered hidden.
|
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 |
isWritable(Path path)
Tests whether a file is writable.
|
static Path |
move(Path source,
Path target,
CopyOption... options)
Move or rename a file to a target file.
|
static SeekableByteChannel |
newByteChannel(Path path,
OpenOption... options)
Opens or creates a file, returning a seekable byte channel to access the
file.
|
static SeekableByteChannel |
newByteChannel(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
Opens or creates a file, returning a seekable byte channel to access the
file.
|
static DirectoryStream<Path> |
newDirectoryStream(Path dir)
Opens a directory, returning a
DirectoryStream to iterate over
all entries in the directory. |
static DirectoryStream<Path> |
newDirectoryStream(Path dir,
DirectoryStream.Filter<? super Path> filter)
Opens a directory, returning a
DirectoryStream to iterate over
the entries in the directory. |
static InputStream |
newInputStream(Path path,
OpenOption... options)
Opens a file, returning an input stream to read from the file.
|
static OutputStream |
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.
|
static <A extends BasicFileAttributes> |
readAttributes(Path path,
Class<A> type,
LinkOption... options)
Reads a file's attributes as a bulk operation.
|
static Path |
setAttribute(Path path,
String attribute,
Object value,
LinkOption... options)
Sets the value of a file attribute.
|
static Path |
setLastModifiedTime(Path path,
FileTime time)
Updates a file's last modified time attribute.
|
static long |
size(Path path)
Returns the size of a file (in bytes).
|
public static Path copy(Path source, Path target, CopyOption... options) throws IOException
This method copies a file to the target file with the options
parameter specifying how the copy is performed. By default, the
copy fails if the target file already exists or is a symbolic link,
except if the source and target are the same
file, in
which case the method completes without copying the file. File attributes
are not required to be copied to the target file. If symbolic links are
supported, and the file is a symbolic link, then the final target of the
link is copied. If the file is a directory then it creates an empty
directory in the target location (entries in the directory are not
copied).
The options
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, the
last-modified-time is
copied to the target file if supported by both the source and target
file store. 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, the COPY_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 an IOException
is thrown then it possible that the target file is incomplete or some of
its file attributes have not been copied from the source file. When the
REPLACE_EXISTING
option is specified and the target file exists,
then the target file is replaced. The check for the existence of the file
and the creation of the new file may not be atomic with respect to other
file system activities.
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 fileoptions
- 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 the
REPLACE_EXISTING
option is not specified (optional
specific exception)DirectoryNotEmptyException
- the REPLACE_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, the checkRead
method is invoked to check read access to the source file, the
checkWrite
is invoked
to check write access to the target file.public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
createDirectory
method, an exception
is not thrown if the directory could not be created because it already
exists.
The attrs
parameter is optional file-attributes
to set atomically when creating the nonexistent
directories. Each file attribute is identified by its name
. 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
- if dir
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, the checkWrite
method is invoked prior to attempting to create a directory and
its checkRead
is
invoked for each parent directory that is checked. If dir
is not an absolute path then its toAbsolutePath
may need to be invoked to get its absolute path.
This may invoke the security manager's checkPropertyAccess
method to check access to the system property user.dir
public static Path createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException
createDirectories
method should be used where it is required to create all nonexistent
parent directories first.
The attrs
parameter is optional file-attributes
to set atomically when creating the directory. Each
attribute is identified by its name
. 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, the checkWrite
method is invoked to check write access to the new directory.public static Path createFile(Path path, FileAttribute<?>... attrs) throws IOException
The attrs
parameter is optional file-attributes
to set atomically when creating the file. Each attribute
is identified by its name
. 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, the checkWrite
method is invoked to check write access to the new file.public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) throws IOException
Path
is associated
with the same FileSystem
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
the prefix
is used to construct candidate names.
As with the createTempFile
methods, this method is only
part of a temporary-file facility.
The attrs
parameter is optional file-attributes
to set atomically when creating the directory. Each
attribute is identified by its name
. 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 be null
attrs
- 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 dir
does not existSecurityException
- In the case of the default provider, and a security manager is
installed, the checkWrite
method is invoked to check write access when creating the
directory.public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException
Path
is
associated with the default FileSystem
.
This method works in exactly the manner specified by createTempDirectory(Path,String,FileAttribute[])
method for the case
that the dir
parameter is the temporary-file directory.
prefix
- the prefix string to be used in generating the directory's name;
may be null
attrs
- 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, the checkWrite
method is invoked to check write access when creating the
directory.public static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
Path
is associated with the same FileSystem
as the given
directory.
The details as to how the name of the file is constructed is implementation dependent and therefore not specified.
As with the File.createTempFile
methods, this method is only
part of a temporary-file facility. Where used as a work files,
the resulting file may be opened using the DELETE_ON_CLOSE
option so that the
file is deleted when the appropriate close
method is invoked.
The attrs
parameter is optional file-attributes
to set atomically when creating the file. Each attribute
is identified by its name
. 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 fileprefix
- the prefix string to be used in generating the file's name;
may be null
suffix
- the suffix string to be used in generating the file's name;
may be null
, 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 dir
does not existSecurityException
- In the case of the default provider, and a security manager is
installed, the checkWrite
method is invoked to check write access to the file.public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
Path
is associated with the default FileSystem
.
This method works in exactly the manner specified by the
createTempFile(Path,String,String,FileAttribute[])
method for
the case that the dir
parameter is the temporary-file directory.
prefix
- the prefix string to be used in generating the file's name;
may be null
suffix
- the suffix string to be used in generating the file's name;
may be null
, 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, the checkWrite
method is invoked to check write access to the file.public static void delete(Path path) throws IOException
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.
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, the SecurityManager.checkDelete(String)
method
is invoked to check delete access to the filepublic static boolean deleteIfExists(Path path) throws IOException
As with the delete(Path)
method, an
implementation may need to examine the file to determine if the file is a
directory. Consequently this method may not be atomic with respect to
other file system operations. If the file is a symbolic link, then the
symbolic link itself, not the final target of the link, is deleted.
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, the SecurityManager.checkDelete(String)
method
is invoked to check delete access to the file.public static boolean exists(Path path, LinkOption... options)
The options
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 option NOFOLLOW_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, the SecurityManager.checkRead(String)
is invoked to check
read access to the file.notExists(java.nio.file.Path, java.nio.file.LinkOption...)
public static Object getAttribute(Path path, String attribute, LinkOption... options) throws IOException
The attribute
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 the name attribute view
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.
The options
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 option NOFOLLOW_LINKS
is present then symbolic links are not followed.
Usage Example:
Suppose we require the size of the file on a system that
supports a "basic
" view:
Path path = ... long size = (Long)Files.getAttribute(path, "basic:size");
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, its checkRead
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 FileStore getFileStore(Path path) throws IOException
FileStore
representing the file store where a file
is located.
Once a reference to the FileStore
is obtained it is
implementation specific if operations on the returned FileStore
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, the checkRead
method is invoked to check read access to the file, and in
addition it checks RuntimePermission
("getFileStoreAttributes")public static FileTime getLastModifiedTime(Path path, LinkOption... options) throws IOException
The options
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 option NOFOLLOW_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, its checkRead
method denies read access to the file.BasicFileAttributes.lastModifiedTime()
public static boolean isDirectory(Path path, LinkOption... options)
The options
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 option NOFOLLOW_LINKS
is present then symbolic links are not followed.
Where is it 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 the readAttributes
method and the file type tested with the BasicFileAttributes.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, its checkRead
method denies read access to the file.public static boolean isHidden(Path path) throws IOException
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, the checkRead
method 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, the checkRead
is invoked to check read access to the file.public static boolean isRegularFile(Path path, LinkOption... options)
The options
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 option NOFOLLOW_LINKS
is present then symbolic links are not followed.
Where is it 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 the readAttributes
method and the file type tested with the BasicFileAttributes.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, its checkRead
method denies read access to the file.public static boolean isSameFile(Path path, Path path2) throws IOException
If both Path
objects are equal
then this method returns true
without checking if the file exists.
This method checks if
both Path
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-null Paths
.
Path
f
,
isSameFile(f,f)
should return true
.
Paths
f
and g
,
isSameFile(f,g)
will equal isSameFile(g,f)
.
Paths
f
, g
, and h
, if isSameFile(f,g)
returns
true
and isSameFile(g,h)
returns true
, then
isSameFile(f,h)
will return return true
.
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, the checkRead
method is invoked to check read access to both files.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, the checkWrite
is invoked to check write access to the file.public static Path move(Path source, Path target, CopyOption... options) throws IOException
By default, this method attempts to move the file to the target
file, failing if the target file exists except if the source and
target are the same
file, in which case this method
has no effect. If the file is a symbolic link then the symbolic link
itself, not the target of the link, is moved. This method may be
invoked to move an empty directory. In some implementations a directory
has entries for special files or links that are created when the
directory is created. In such implementations a directory is considered
empty when only the special entries exist. When invoked to move a
directory that is not empty then the directory is moved if it does not
require moving the entries in the directory. For example, renaming a
directory on the same FileStore
will usually not require moving
the entries in the directory. When moving a directory requires that its
entries be moved then this method fails (by throwing an IOException
).
The options
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 an IOException . If the move cannot be
performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for
example, when the target location is on a different FileStore
and would require that the file be copied. |
An implementation of this interface may support additional implementation specific options.
Where the move requires that the file be copied then the last-modified-time
is copied to the
new file. 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 a IOException
is thrown, then the state of the files is not defined. The
original file and the target file may both exist, the target file may be
incomplete or some of its file attributes may not been copied from the
original file.
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 fileoptions
- 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 the
REPLACE_EXISTING
option is not specified (optional
specific exception)DirectoryNotEmptyException
- the REPLACE_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 the ATOMIC_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, the checkWrite
method is invoked to check write access to both the source and
target file.public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException
This method opens or creates a file in exactly the manner specified
by the newByteChannel
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 the CREATE_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, the checkRead
method is invoked to check read access to the path if the file is
opened for reading. The checkWrite
method is invoked to check write access to the path
if the file is opened for writing. The checkDelete
method is
invoked to check delete access if the file is opened with the
DELETE_ON_CLOSE
option.FileChannel.open(Path,OpenOption[])
public static SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException
The options
parameter determines how the file is opened.
The READ
and WRITE
options determine if the file should be
opened for reading and/or writing. If neither option (or the APPEND
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 to READ
and WRITE
, 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's write method first advances
the position to the end of the file and then writes the requested
data. Whether the advancement of the position and the writing of the
data are done in a single atomic operation is system-dependent and
therefore unspecified. This option may not be used in conjunction
with the READ or TRUNCATE_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 the
CREATE_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 a
best effort attempt to delete the file when closed by the
close method. If the close
method is not invoked then a best effort attempt is made to
delete the file when the Java virtual machine terminates. |
SPARSE |
When creating a new file this option is a hint 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.
The attrs
parameter is optional file-attributes
to set atomically when a new file is created.
In the case of the default provider, the returned seekable byte channel
is a FileChannel
.
Usage Examples:
Path path = ...
// open file for reading
Set<StandardOpenOption> readmode = new HashSet<>();
readmode.add(READ);
ReadableByteChannel rbc = Files.newByteChannel(path, readmode);
// open file for writing to the end of an existing file, creating
// the file if it doesn't already exist
Set<StandardOpenOption> appendmode = new HashSet<>();
appendmode.add(CREATE);
appendmode.add(APPEND);
WritableByteChannel wbc = Files.newByteChannel(path, appendmode);
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 the CREATE_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, the checkRead
method is invoked to check read access to the path if the file is
opened for reading. The checkWrite
method is invoked to check write access to the path
if the file is opened for writing. The checkDelete
method is
invoked to check delete access if the file is opened with the
DELETE_ON_CLOSE
option.FileChannel.open(Path,Set,FileAttribute[])
public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException
DirectoryStream
to iterate over
all entries in the directory. The elements returned by the directory
stream's iterator
are of type Path
, each one representing an entry in the directory. The Path
objects are obtained as if by resolving
the
name of the directory entry against dir
.
When not using the try-with-resources construct, then directory
stream's close
method should be invoked after iteration is
completed so as to free any resources held for the open directory.
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, the checkRead
method is invoked to check read access to the directory.public static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException
DirectoryStream
to iterate over
the entries in the directory. The elements returned by the directory
stream's iterator
are of type Path
, each one representing an entry in the directory. The Path
objects are obtained as if by resolving
the
name of the directory entry against dir
. The entries returned by
the iterator are filtered by the given filter
.
When not using the try-with-resources construct, then directory
stream's close
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 the hasNext
or next
method. Where an IOException
is thrown, it results in the hasNext
or next
method throwing a DirectoryIteratorException
with the
IOException
as the cause.
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, the checkRead
method is invoked to check read access to the directory.public static InputStream newInputStream(Path path, OpenOption... options) throws IOException
mark
or reset
methods. The
stream will be safe for access by multiple concurrent threads. Reading
commences at the beginning of the file. Whether the returned stream is
asynchronously closeable and/or interruptible is highly
file system provider specific and therefore not specified.
The options
parameter determines how the file is opened.
If no options are present then it is equivalent to opening the file with
the READ
option. In addition to the READ
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, the checkRead
method is invoked to check read access to the file.public static OutputStream newOutputStream(Path path, OpenOption... options) throws IOException
This method opens or creates a file in exactly the manner specified
by the newByteChannel
method with the exception that the READ
option may not be present in the array of options. If no options are
present then this method works as if the CREATE
, TRUNCATE_EXISTING
,
and WRITE
options are present. In other
words, it opens the file for writing, creating the file if it doesn't
exist, or initially truncating an existing regular-file
to a size of 0
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
- if options
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, the checkWrite
method is invoked to check write access to the file. The checkDelete
method is
invoked to check delete access if the file is opened with the
DELETE_ON_CLOSE
option.public static boolean notExists(Path path, LinkOption... options)
The options
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 option NOFOLLOW_LINKS
is present then symbolic links are not followed.
Note that this method is not the complement of the exists
method. Where it is not possible to determine if a file exists
or not then both methods return false
. As with the exists
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, the SecurityManager.checkRead(String)
is invoked to check
read access to the file.public static <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException
The type
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 a type
parameter of BasicFileAttributes.class
will not throw UnsupportedOperationException
.
The options
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 option NOFOLLOW_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);
A
- the type of attribute to readpath
- the path to the filetype
- the Class
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, its checkRead
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) throws IOException
The attribute
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 the name of an attribute view
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.
The options
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 option NOFOLLOW_LINKS
is present then symbolic links are not followed.
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, its checkWrite
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 Path setLastModifiedTime(Path path, FileTime time) throws IOException
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's checkWrite
method is invoked
to check write access to filepublic static long size(Path path) throws IOException
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, its checkRead
method denies read access to the file.BasicFileAttributes.size()
Copyright (c) 2014, Oracle and/or its affiliates. All Rights Reserved. Use of this specification is subject to license terms.