Class MoreFiles
Files.- Since:
- 5.11
-
Method Summary
Modifier and TypeMethodDescriptionstatic booleanAn NFS-safe version ofFiles.exists(Path, LinkOption...)} which actually opens the file to verify its existence.static voidcleanDirectory(Path directory) Deletes any files or subdirectories in the specified directory and leaves the directory empty.static voiddeleteOnExit(Path path) Registers the provided path to be deleted when the JVM exits.static booleandeleteQuietly(Path path) Recursively deletesthe specified path, suppressing anyIOExceptions that are thrown.static voiddeleteRecursively(Path path) Recursively deletes the specified path.static longgetLastModified(Path path) Gets thelast modified timefor the specifiedPath, in milliseconds.static booleanisAclSupported(Path path) Gets thefile storefor the specifiedPath, and returns whether the file store supports ACLs.static booleanisPosixSupported(Path path) Gets thefile storefor the specifiedPath, and returns whether the file store supports POSIX.static booleanReturnstrueif the specified path is contained within theexpectedParent.static PathCreates the specifieddirectory, if it does not already exist.static PathCreates the specifiedchilddirectory beneath theparent, if it does not already exist.static StringCreates a path-safe version of a string, replacing all potentially unsafe characters with a-character.static voidrequireWithin(Path path, Path expectedParent) Validates that the specified path is contained within theexpectedParent.static PathSimplifiesresolvingseveral subpaths in a single call.static voidsetPermissions(SetFilePermissionRequest request) Sets the file permissions according to the specifications provided in therequest.static longstatic StringReads the entire contents of the specified path using the UTF-8 character set.static StringReads the entire contents of the specified path using the provided character set.static longCalculates the total size of the specified path.static voidCreatesthe specified path, if it doesn't exist, orsets its last modified timeif it does.static Pathwrite(Path path, String value, Charset charset, OpenOption... options) Writes the provided value to the specified path using the provided character set.static Pathwrite(Path path, String value, OpenOption... options) Writes the provided value to the specified path using the UTF-8 character set.
-
Method Details
-
canOpen
An NFS-safe version ofFiles.exists(Path, LinkOption...)} which actually opens the file to verify its existence.NFS can cache file stat information, which can lead to
Files.exists(Path, LinkOption...)} returningtruefor files that no longer exist when files are deleted on other nodes. The only way to ensure the file really exists is to open it, which won't be fooled by cached stat information.- Parameters:
path- the path to the file to test- Returns:
trueif the file can be opened; otherwise,falseif not- Since:
- 7.16
-
cleanDirectory
Deletes any files or subdirectories in the specified directory and leaves the directory empty.- Parameters:
directory- the directory to clean- Throws:
IOException- if the path does not denote a directory, or the directory's contents could not be deleted
-
deleteOnExit
Registers the provided path to be deleted when the JVM exits.Delete-on-exit is performed on a best-effort basis, and should not be relied upon as the primary solution for deleting files. Additionally, it only works for files and empty directories.
- Parameters:
path- the path to register for deletion when the JVM exits- See Also:
-
deleteQuietly
Recursively deletesthe specified path, suppressing anyIOExceptions that are thrown.- Parameters:
path- the path to delete, which may be a file or a directory- Returns:
trueif the path was deleted; otherwise,falseif it did not exist or could not be deleted
-
deleteRecursively
Recursively deletes the specified path.If the specified
Pathdenotes a directory, the directory's contents are recursively deleted, depth-first, to empty the directory so it can be deleted. If any files or subdirectories can't be deleted, an exception will be thrown. Note that some files and subdirectories may have been deleted prior to the exception being thrown. Additionally, if the directory contains any symbolic links the links themselves are deleted, not their targets.If the specified
Pathdenotes a symbolic link, the symbolic link itself is deleted, rather than the target of the link. If the path is a symbolic link to a directory, that directory's contents are not removed.If the specified
Pathdenotes a file, it is deleted.If the specified path does not exist, nothing happens and no exception is thrown.
- Parameters:
path- the path to delete, which may be a file or a directory- Throws:
IOException- if the specified path cannot be deleted
-
getLastModified
Gets thelast modified timefor the specifiedPath, in milliseconds.Like
File.lastModified(), if the path does not exist or its attributes cannot be read,0Lis returned rather than throwing an exception. UseFiles.getLastModifiedTime(java.nio.file.Path, java.nio.file.LinkOption...)directly if an exception is desired.- Parameters:
path- the path to retrieve the last modified time for- Returns:
- the file's last modified time, in milliseconds, or
0Lif the time could not be determined
-
isAclSupported
Gets thefile storefor the specifiedPath, and returns whether the file store supports ACLs. NTFS on Windows supports ACLs, but most Linux filesystems, and APFS and HFS+ on macOS, do not; they usePOSIXinstead.- Parameters:
path- the path to check, which is used to find the appropriatefile store- Returns:
trueif the path'sfile storesupports ACLs; otherwise,false- Throws:
IOException- if thefile storecannot be determined for the specified path- Since:
- 6.2
-
isPosixSupported
Gets thefile storefor the specifiedPath, and returns whether the file store supports POSIX. Most Linux filesystems support POSIX, as do APFS and HFS+ on macOS, but, for example, NTFS on Windows does not; it usesACLsinstead.- Parameters:
path- the path to check, which is used to find the appropriatefile store- Returns:
trueif the path'sfile storesupports POSIX; otherwise,false- Throws:
IOException- if thefile storecannot be determined for the specified path- Since:
- 6.2
-
isWithin
Returnstrueif the specified path is contained within theexpectedParent. This should be used to ensure paths created with user-entered data don't "escape" the specified parent, to prevent path traversal attacks.- Parameters:
path- the path to validateexpectedParent- the required parent directory- Returns:
trueifpathis contained withinexpectedParent; otherwise,false- Throws:
IllegalArgumentException- ifexpectedParentdoes not exist or is not a directoryIOException- if the real path for either of the provided paths cannot be resolved
-
mkdir
Creates the specifieddirectory, if it does not already exist. If the path does exist, it is validated that it is a directory and not a file.- Parameters:
directory- the directory to create- Returns:
- the created directory
- Throws:
IllegalStateException- if thedirectorypath already exists and is not a directory, or if the directory cannot be createdNullPointerException- if the provideddirectoryisnull
-
mkdir
Creates the specifiedchilddirectory beneath theparent, if it does not already exist. If the path does exist, it is validated that it is a directory and not a file.- Parameters:
parent- the base path for creating the new directorychild- the path beneath the parent for the new directory- Returns:
- the created directory
- Throws:
IllegalArgumentException- if thechildpath is blank or emptyIllegalStateException- if thechildpath already exists and is not a directory, or if the directory cannot be createdNullPointerException- if the providedparentorchildisnull
-
pathSafe
Creates a path-safe version of a string, replacing all potentially unsafe characters with a-character.- Parameters:
value- the value to transform into a path safe string- Returns:
- the path safe string
- Since:
- 7.16
-
requireWithin
public static void requireWithin(@Nonnull Path path, @Nonnull Path expectedParent) throws IOException Validates that the specified path is contained within theexpectedParent. This should be used to ensure paths created with user-entered data don't "escape" the specified parent, to prevent path traversal attacks.- Parameters:
path- the path to validateexpectedParent- the required parent directory- Throws:
IllegalArgumentException- ifexpectedParentdoes not exist or is not a directory, or ifpathis not contained within itIOException- if the real path for either of the provided paths cannot be resolved
-
resolve
@Nonnull public static Path resolve(@Nonnull Path path, @Nonnull String first, @Nonnull String... more) Simplifiesresolvingseveral subpaths in a single call.- Parameters:
path- the base path, from which subpaths should be resolvedfirst- the first subpath, used to enforce that at least a single subpath is providedmore- zero or more additional subpaths- Returns:
- the resolved path
-
setPermissions
Sets the file permissions according to the specifications provided in therequest. For Unix systems this will map the provided permissions to the correspondingPosixFilePermission. For Windows systemsACL entrieswill be put together as follows:Owner permissions: These will be applied to theowner principal. Also, for convenience, they will be applied to theAdministratorgroup (if it exists) since its members can override ACLs anywayWorld permissions: These will be applied to theEveryonegroup.Group permissions: These will be ignored. In POSIX-compliant OSes files and directories are associated with both a user and a group and the permission model explicitly provides for setting a group permission agnostic of the group's name. The ACL model used by Windows requires knowing the name of the group you want to provision.
- Parameters:
request- describes the file permissions to set- Throws:
IllegalArgumentException- if the providedpathdoes not exist, or exists and is not a regular fileIOException- if the real path for either of the provided paths cannot be resolved
-
size
Gets thesizeof the specifiedPath.Like
File.length(), if the path does not exist or its attributes cannot be read,0Lis returned rather than throwing an exception. UseFiles.size(java.nio.file.Path)directly if an exception is desired.- Parameters:
path- the path to retrieve the size of- Returns:
- the file's size, or
0Lif the size could not be determined
-
totalSize
Calculates the total size of the specified path.If the specified
Pathdenotes a directory, its contents are recursively traversed to compute its overall size. For directories containing a large number of files this can be quite slow, so it should be used with caution.If the specified
Pathdenotes a symbolic link, its size (generally the length of its target path) is reported. Symbolic links are not followed.If the specified
Pathdenotes a file, its size is reported.- Parameters:
path- the path to calculate a size for- Returns:
- the calculated size, or
0Lif the size could not be calculated
-
touch
Createsthe specified path, if it doesn't exist, orsets its last modified timeif it does.- Parameters:
path- the path to create or set a last modification time for- Throws:
IOException- if a nonexistent file cannot be created, or if the last modification time cannot be set for an existing file
-
toString
Reads the entire contents of the specified path using the UTF-8 character set.Callers should exercise caution when using this method, as it may result in reading a significant amount of data into memory. Where possible, callers are encouraged to stream file contents instead.
- Parameters:
path- the path to read- Returns:
- the file's contents
- Throws:
IOException- if the file cannot be read
-
toString
@Nonnull public static String toString(@Nonnull Path path, @Nonnull Charset charset) throws IOException Reads the entire contents of the specified path using the provided character set.Callers should exercise caution when using this method, as it may result in reading a significant amount of data into memory. Where possible, callers are encouraged to stream file contents instead.
- Parameters:
path- the path to readcharset- the character set to use to decode the file's contents- Returns:
- the file's contents
- Throws:
IOException- if the file cannot be read
-
write
@Nonnull public static Path write(@Nonnull Path path, @Nonnull String value, @Nonnull OpenOption... options) throws IOException Writes the provided value to the specified path using the UTF-8 character set.- Parameters:
path- the path to writevalue- the value to writeoptions-OpenOptions to control how the path is accessed- Returns:
- the provided path
- Throws:
IOException- if the file cannot be written
-
write
@Nonnull public static Path write(@Nonnull Path path, @Nonnull String value, @Nonnull Charset charset, @Nonnull OpenOption... options) throws IOException Writes the provided value to the specified path using the provided character set.- Parameters:
path- the path to writevalue- the value to writecharset- the character set to use to encode the value to bytesoptions-OpenOptions to control how the path is accessed- Returns:
- the provided path
- Throws:
IOException- if the file cannot be written
-