java.lang.Object
org.eclipse.jgit.util.FileUtils
File Utilities
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interface -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intOption to only delete empty directories.static final intOption not to throw exceptions when a deletion finally doesn't succeed.static final intOption to delete givenFilestatic final intOption to recursively delete givenFilestatic final intOption to retry deletion if not successfulstatic final intOption to skip deletion if file doesn't exist -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic booleancanExecute(File file) Whether the given file can be executed.static Filecanonicalize(File file) Best-effort variation ofFile.getCanonicalFile()returning the input file if the file cannot be canonicalized instead of throwingIOException.static voidAtomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.static PathcreateSymLink(File path, String target) Create a symbolic linkstatic FilecreateTempDir(String prefix, String suffix, File dir) Create a temporary directory.static longdelay(long last, long min, long max) Compute a delay in amin..maxinterval with random jitter.static voidDelete file or empty folderstatic voidDelete file or folderstatic FS.AttributesgetFileAttributesPosix(FS fs, File file) Get file system attributes for the given file.static longGet file lengthstatic booleanWhether the path is a directory with files in it.static booleanDetermine if an IOException is a stale NFS file handlestatic booleanisStaleFileHandleInCausalChain(Throwable throwable) Determine if a throwable or a cause in its causal chain is a stale NFS file handlestatic voidCreates the directory named by this abstract pathname.static voidCreates the directory named by this abstract pathname.static voidCreates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.static voidCreates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.static FileNFC normalize a file (on Mac), otherwise do nothingstatic StringOn Mac: get NFC normalized form of given name, otherwise the given name.static StringpathToString(File file) Convert a path to String, replacing separators as necessary.static StringreadSymLink(File path) Read target path of the symlink.static <T> TreadWithRetries(File file, FileUtils.IOFunction<File, ? extends T> reader) Invokes the givenFileUtils.IOFunction, performing a limited number of re-tries if exceptions occur that indicate either a stale NFS file handle or that indicate that the file may be written concurrently.static StringrelativizeGitPath(String base, String other) Expressesotheras a relative file path frombase.static StringrelativizeNativePath(String base, String other) Expressesotheras a relative file path frombase.static StringrelativizePath(String base, String other, String dirSeparator, boolean caseSensitive) Expressesotheras a relative file path frombasestatic voidRename a file or folder.static voidrename(File src, File dst, CopyOption... options) Rename a file or folder using the passedCopyOptions.static voidSet a file hidden (on Windows)static Pathstatic voidTouch the given file
-
Field Details
-
NONE
public static final int NONEOption to delete givenFile- See Also:
-
RECURSIVE
public static final int RECURSIVEOption to recursively delete givenFile- See Also:
-
RETRY
public static final int RETRYOption to retry deletion if not successful- See Also:
-
SKIP_MISSING
public static final int SKIP_MISSINGOption to skip deletion if file doesn't exist- See Also:
-
IGNORE_ERRORS
public static final int IGNORE_ERRORSOption not to throw exceptions when a deletion finally doesn't succeed.- Since:
- 2.0
- See Also:
-
EMPTY_DIRECTORIES_ONLY
public static final int EMPTY_DIRECTORIES_ONLYOption to only delete empty directories. This option can be combined withRECURSIVE- Since:
- 3.0
- See Also:
-
-
Constructor Details
-
FileUtils
public FileUtils()
-
-
Method Details
-
toPath
- Parameters:
f-Fileto be converted toPath- Returns:
- the path represented by the file
- Throws:
IOException- in case the path represented by the file is not valid (InvalidPathException)- Since:
- 4.10
-
delete
Delete file or empty folder- Parameters:
f-Fileto be deleted- Throws:
IOException- if deletion offfails. This may occur iffdidn't exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to delete the same file.
-
delete
Delete file or folder- Parameters:
f-Fileto be deletedoptions- deletion options,RECURSIVEfor recursive deletion of a subtree,RETRYto retry when deletion failed. Retrying may help if the underlying file system doesn't allow deletion of files being read by another thread.- Throws:
IOException- if deletion offfails. This may occur iffdidn't exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to delete the same file. This exception is not thrown when IGNORE_ERRORS is set.
-
rename
Rename a file or folder. If the rename fails and if we are running on a filesystem where it makes sense to repeat a failing rename then repeat the rename operation up to 9 times with 100ms sleep time between two calls. Furthermore if the destination exists and is directory hierarchy with only directories in it, the whole directory hierarchy will be deleted. If the target represents a non-empty directory structure, empty subdirectories within that structure may or may not be deleted even if the method fails. Furthermore if the destination exists and is a file then the file will be deleted and then the rename is retried.This operation is not atomic.
- Parameters:
src- the oldFiledst- the newFile- Throws:
IOException- if the rename has failed- Since:
- 3.0
- See Also:
-
rename
public static void rename(File src, File dst, CopyOption... options) throws AtomicMoveNotSupportedException, IOException Rename a file or folder using the passedCopyOptions. If the rename fails and if we are running on a filesystem where it makes sense to repeat a failing rename then repeat the rename operation up to 9 times with 100ms sleep time between two calls. Furthermore if the destination exists and is a directory hierarchy with only directories in it, the whole directory hierarchy will be deleted. If the target represents a non-empty directory structure, empty subdirectories within that structure may or may not be deleted even if the method fails. Furthermore if the destination exists and is a file then the file will be replaced ifStandardCopyOption.REPLACE_EXISTINGhas been set. IfStandardCopyOption.ATOMIC_MOVEhas been set the rename will be done atomically or fail with anAtomicMoveNotSupportedException- Parameters:
src- the old filedst- the new fileoptions- options to pass toFiles.move(java.nio.file.Path, java.nio.file.Path, CopyOption...)- Throws:
AtomicMoveNotSupportedException- if file cannot be moved as an atomic file system operationIOException- if an IO error occurred- Since:
- 4.1
-
mkdir
Creates the directory named by this abstract pathname.- Parameters:
d- directory to be created- Throws:
IOException- if creation ofdfails. This may occur ifddid exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to create the same directory.
-
mkdir
Creates the directory named by this abstract pathname.- Parameters:
d- directory to be createdskipExisting- iftrueskip creation of the given directory if it already exists in the file system- Throws:
IOException- if creation ofdfails. This may occur ifddid exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to create the same directory.
-
mkdirs
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.- Parameters:
d- directory to be created- Throws:
IOException- if creation ofdfails. This may occur ifddid exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to create the same directory.
-
mkdirs
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.- Parameters:
d- directory to be createdskipExisting- iftrueskip creation of the given directory if it already exists in the file system- Throws:
IOException- if creation ofdfails. This may occur ifddid exist when the method was called. This can therefore cause java.io.IOExceptions during race conditions when multiple concurrent threads all try to create the same directory.
-
createNewFile
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The
FileLockfacility should be used instead.- Parameters:
f- the file to be created- Throws:
IOException- if the named file already exists or if an I/O error occurred
-
createSymLink
Create a symbolic link- Parameters:
path- the path of the symbolic link to createtarget- the target of the symbolic link- Returns:
- the path to the symbolic link
- Throws:
IOException- if an IO error occurred- Since:
- 4.2
-
readSymLink
Read target path of the symlink.- Parameters:
path- aFileobject.- Returns:
- target path of the symlink, or null if it is not a symbolic link
- Throws:
IOException- if an IO error occurred- Since:
- 3.0
-
createTempDir
Create a temporary directory.- Parameters:
prefix- prefix stringsuffix- suffix stringdir- The parent dir, can be null to use system default temp dir.- Returns:
- the temp dir created.
- Throws:
IOException- if an IO error occurred- Since:
- 3.4
-
relativizeNativePath
Expressesotheras a relative file path frombase. File-separator and case sensitivity are based on the current file system. See alsorelativizePath(String, String, String, boolean).- Parameters:
base- Base pathother- Destination path- Returns:
- Relative path from
basetoother - Since:
- 4.8
-
relativizeGitPath
Expressesotheras a relative file path frombase. File-separator and case sensitivity are based on Git's internal representation of files (which matches Unix). See alsorelativizePath(String, String, String, boolean).- Parameters:
base- Base pathother- Destination path- Returns:
- Relative path from
basetoother - Since:
- 4.8
-
relativizePath
public static String relativizePath(String base, String other, String dirSeparator, boolean caseSensitive) Expressesotheras a relative file path frombaseFor example, if called with the two following paths :
This will return "..\\another_project\\pom.xml".base = "c:\\Users\\jdoe\\eclipse\\git\\project"other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"Note that this will return the empty String if
baseandotherare equal.- Parameters:
base- The path against whichothershould be relativized. This will be assumed to denote the path to a folder and not a file.other- The path that will be made relative tobase.dirSeparator- A string that separates components of the path. In practice, this is "/" or "\\".caseSensitive- Whether to consider differently-cased directory names as distinct- Returns:
- A relative path that, when resolved against
base, will yield the originalother. - Since:
- 4.8
-
isStaleFileHandle
Determine if an IOException is a stale NFS file handle- Parameters:
ioe- anIOExceptionobject.- Returns:
- a boolean true if the IOException is a stale NFS file handle
- Since:
- 4.1
-
isStaleFileHandleInCausalChain
Determine if a throwable or a cause in its causal chain is a stale NFS file handle- Parameters:
throwable- aThrowableobject.- Returns:
- a boolean true if the throwable or a cause in its causal chain is a stale NFS file handle
- Since:
- 4.7
-
readWithRetries
public static <T> T readWithRetries(File file, FileUtils.IOFunction<File, ? extends T> reader) throws ExceptionInvokes the givenFileUtils.IOFunction, performing a limited number of re-tries if exceptions occur that indicate either a stale NFS file handle or that indicate that the file may be written concurrently.- Type Parameters:
T- result type- Parameters:
file- to readreader- for reading the file and creating an instance ofT- Returns:
- the result of the
reader, ornullif the file does not exist - Throws:
Exception- if a problem occurs- Since:
- 6.2
-
setHidden
Set a file hidden (on Windows)- Parameters:
file- aFileobject.hidden- a boolean.- Throws:
IOException- if an IO error occurred- Since:
- 4.1
-
getLength
Get file length- Parameters:
file- aFile.- Returns:
- length of the given file
- Throws:
IOException- if an IO error occurred- Since:
- 4.1
-
hasFiles
Whether the path is a directory with files in it.- Parameters:
dir- directory path- Returns:
trueif the given directory path contains files- Throws:
IOException- on any I/O errors accessing the path- Since:
- 5.11
-
canExecute
Whether the given file can be executed.- Parameters:
file- aFileobject.- Returns:
trueif the given file can be executed.- Since:
- 4.1
-
getFileAttributesPosix
Get file system attributes for the given file. -
normalize
NFC normalize a file (on Mac), otherwise do nothing -
normalize
On Mac: get NFC normalized form of given name, otherwise the given name.- Parameters:
name- aStringobject.- Returns:
- on Mac: NFC normalized form of given name
- Since:
- 4.1
-
canonicalize
Best-effort variation ofFile.getCanonicalFile()returning the input file if the file cannot be canonicalized instead of throwingIOException.- Parameters:
file- to be canonicalized; may benull- Returns:
- canonicalized file, or the unchanged input file if
canonicalization failed or if
file == null - Throws:
SecurityException- ifFile.getCanonicalFile()throws one- Since:
- 4.2
-
pathToString
Convert a path to String, replacing separators as necessary.- Parameters:
file- aFile.- Returns:
- file's path as a String
- Since:
- 4.10
-
touch
Touch the given file- Parameters:
f- the file to touch- Throws:
IOException- if an IO error occurred- Since:
- 5.1.8
-
delay
public static long delay(long last, long min, long max) Compute a delay in amin..maxinterval with random jitter.- Parameters:
last- amount of delay waited before the last attempt. This is used to seed the next delay interval. Should be 0 if there was no prior delay.min- shortest amount of allowable delay between attempts.max- longest amount of allowable delay between attempts.- Returns:
- new amount of delay to wait before the next attempt.
- Since:
- 5.6
-