Class FileUtils
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidCreates a file if it doesn't already exist usingFile.createNewFile().static FilecreateTempFile(String name) Create a temporary file with the specified name.static FilecreateTempFile(String name, String contents) Create a temporary file with the specified name and specified contents.static booleandeleteFile(File f) Recursively deletes a file or directory.static booleanfileExists(File dir, String fileName) Returnstrue if the specified file exists in the specified directory.static StringgetBaseName(String name) Strips the extension from a file name.static StringgetFileExtension(String name) Returns the extension from a file name.static StringgetFileName(String path) Given an arbitrary path, returns the file name portion of that path.static booleanhasExtension(String name, String ext) Returnstrue if the specified file name contains the specified extension.static FileSame asFile.mkdirs()except throws a RuntimeExeption if directory could not be created.static FileSame asmkdirs(String, boolean)but uses String path.static voidUpdates the modified timestamp on the specified file.resolveSafely(File rootDir, String userPath) Resolves a user-supplied path string against a root directory with a strict filesystem-boundary check — rejects any path that escapes the root (via../, absolute-path injection, symlinks pointing outside, etc.).static StringresolveVirtualPathSafely(String basePath, String userPath) Virtual-path variant ofresolveSafely(File, String)for use with servlet-context paths, classpath resource lookups, or other virtual-path resolvers where no filesystem operation is desired.
-
Method Details
-
create
Creates a file if it doesn't already exist usingFile.createNewFile().Throws a
RuntimeExceptionif the file could not be created.- Parameters:
f- The file to create. Must not benull .
-
createTempFile
Create a temporary file with the specified name.The name is broken into file name and suffix, and the parts are passed to
File.createTempFile(String, String).File.deleteOnExit()is called on the resulting file before being returned by this method.- Parameters:
name- The file name. Must not benull (unguarded — anull name throwsNullPointerException).- Returns:
- A newly-created temporary file.
- Throws:
IOException- Thrown by underlying stream.
-
createTempFile
Create a temporary file with the specified name and specified contents.The name is broken into file name and suffix, and the parts are passed to
File.createTempFile(String, String).File.deleteOnExit()is called on the resulting file before being returned by this method.- Parameters:
name- The file name. Must not benull (unguarded — anull name throwsNullPointerException).contents- The file contents. Can benull (creates an empty file).- Returns:
- A newly-created temporary file.
- Throws:
IOException- Thrown by underlying stream.
-
deleteFile
Recursively deletes a file or directory.- Parameters:
f- The file or directory to delete. Can benull (returnstrue ).- Returns:
true if file or directory was successfully deleted.
-
fileExists
Returnstrue if the specified file exists in the specified directory.- Parameters:
dir- The directory. Can benull (returnsfalse ).fileName- The file name. Can benull (returnsfalse ).- Returns:
true if the specified file exists in the specified directory.
-
getBaseName
Strips the extension from a file name.- Parameters:
name- The file name.- Returns:
- The file name without the extension, or
null if name wasnull .
-
getFileExtension
Returns the extension from a file name.- Parameters:
name- The file name.- Returns:
- The the extension, or
null if name wasnull .
-
getFileName
Given an arbitrary path, returns the file name portion of that path.- Parameters:
path- The path to check. Can benull or empty (returnsnull ).- Returns:
- The file name, or
null if the path wasnull , empty, or contained only slashes.
-
hasExtension
Returnstrue if the specified file name contains the specified extension.- Parameters:
name- The file name. Can benull (returnsfalse ).ext- The extension. Can benull (returnsfalse ).- Returns:
true if the specified file name contains the specified extension.
-
mkdirs
Same asFile.mkdirs()except throws a RuntimeExeption if directory could not be created.- Parameters:
f- The directory to create. Must not benull .clean- Iftrue , deletes the contents of the directory if it already exists.- Returns:
- The same file.
- Throws:
RuntimeException- if directory could not be created.
-
mkdirs
Same asmkdirs(String, boolean)but uses String path.- Parameters:
path- The path of the directory to create. Must not benull clean- Iftrue , deletes the contents of the directory if it already exists.- Returns:
- The directory.
-
resolveSafely
Resolves a user-supplied path string against a root directory with a strict filesystem-boundary check — rejects any path that escapes the root (via../, absolute-path injection, symlinks pointing outside, etc.).Resolves both
rootDirand the resolved target viaPath.toRealPath()+Path.normalize()to handle symlinks deterministically, then assertstarget.startsWith(root)before returning the resolvedFile.Symlinks inside
rootDirthat resolve insiderootDirare followed silently. Symlinks that resolve outsiderootDirare rejected withIllegalArgumentException(callers should map to a403 Forbidden).Pre-existence semantics: when the resolved target does not exist on the filesystem, the helper returns
Optional.empty()so the caller can map to a404 Not Found. Boundary violation always wins over pre-existence — even a non-existent path that escapesrootDir(after../normalization) is rejected withIllegalArgumentExceptionrather thanOptional.empty().Used by
DirectoryResource,LogsResource, and any other resource that resolves an HTTP-supplied path under a configured root directory.- Parameters:
rootDir- The configured root directory. Must not benull .userPath- The user-supplied path, relative torootDir. May benull or empty — in which case the helper returns the resolved root itself.- Returns:
- An
Optionalcontaining the resolvedFileif it exists insiderootDir, orOptional.empty()if the target does not exist. - Throws:
IllegalArgumentException- If the resolved target escapesrootDir, or if the supplieduserPathis not a valid path string. Callers should map to403 Forbidden.
-
resolveVirtualPathSafely
Virtual-path variant ofresolveSafely(File, String)for use with servlet-context paths, classpath resource lookups, or other virtual-path resolvers where no filesystem operation is desired.Operates purely on the virtual path string — no
toRealPath()call, no filesystem touch, no symlink resolution. Safe to use against base paths whose resources do not exist on the local filesystem at all (e.g./WEB-INF/views/inside a Spring Boot fat jar, or a classpath URL).Normalizes the combined path by walking segments and applying
./(drop) and../(pop) semantics, then asserts the result stays under the normalizedbasePath.../segments that would pop abovebasePathare rejected.URL-encoding is the caller's responsibility — this helper treats the literal
%2e%2eas a normal path segment (not as..). Callers that receive user input from URLs should URL-decode before calling.- Parameters:
basePath- The configured base path (virtual; e.g."/WEB-INF/views/"). Must not benull or blank.userPath- The user-supplied path, relative tobasePath. May benull or empty — in which case the helper returns the normalizedbasePath.- Returns:
- The resolved virtual path string (always starting with
basePath). - Throws:
IllegalArgumentException- If the resolved target escapesbasePath, or ifbasePathisnull or blank. Callers should map to403 Forbidden.
-
modifyTimestamp
Updates the modified timestamp on the specified file.Method ensures that the timestamp changes even if it's been modified within the past millisecond.
- Parameters:
f- The file to modify the modified timestamp on. Must not benull .
-