Package org.eclipse.jgit.util
Class FileUtils
- java.lang.Object
-
- org.eclipse.jgit.util.FileUtils
-
public class FileUtils extends java.lang.ObjectFile Utilities
-
-
Field Summary
Fields Modifier and Type Field Description static intEMPTY_DIRECTORIES_ONLYOption to only delete empty directories.static intIGNORE_ERRORSOption not to throw exceptions when a deletion finally doesn't succeed.private static org.slf4j.LoggerLOGstatic intNONEOption to delete givenFilestatic intRECURSIVEOption to recursively delete givenFilestatic intRETRYOption to retry deletion if not successfulprivate static java.util.RandomRNGstatic intSKIP_MISSINGOption to skip deletion if file doesn't exist
-
Constructor Summary
Constructors Constructor Description FileUtils()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static booleancanExecute(java.io.File file)Whether the given file can be executed.static java.io.Filecanonicalize(java.io.File file)Best-effort variation ofFile.getCanonicalFile()returning the input file if the file cannot be canonicalized instead of throwingIOException.static voidcreateNewFile(java.io.File f)Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.static java.nio.file.PathcreateSymLink(java.io.File path, java.lang.String target)Create a symbolic linkstatic java.io.FilecreateTempDir(java.lang.String prefix, java.lang.String suffix, java.io.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(java.io.File f)Delete file or empty folderstatic voiddelete(java.io.File f, int options)Delete file or folder(package private) static booleanexists(java.io.File file)(package private) static java.nio.file.attribute.BasicFileAttributesfileAttributes(java.io.File file)Return all the attributes of a file, without following symbolic links.(package private) static FS.AttributesgetFileAttributesBasic(FS fs, java.io.File file)static FS.AttributesgetFileAttributesPosix(FS fs, java.io.File file)Get file system attributes for the given file.static longgetLength(java.io.File file)Get file lengthprivate static voidhandleDeleteException(java.io.File f, java.io.IOException e, int allOptions, int checkOptions)static booleanhasFiles(java.nio.file.Path dir)Whether the path is a directory with files in it.(package private) static booleanisDirectory(java.io.File file)(package private) static booleanisFile(java.io.File file)(package private) static booleanisHidden(java.io.File file)static booleanisStaleFileHandle(java.io.IOException ioe)Determine if an IOException is a Stale NFS File Handlestatic booleanisStaleFileHandleInCausalChain(java.lang.Throwable throwable)Determine if a throwable or a cause in its causal chain is a Stale NFS File Handle(package private) static booleanisSymlink(java.io.File file)(package private) static longlastModified(java.io.File file)Deprecated.uselastModifiedInstant(Path)instead which returns FileTime(package private) static java.time.InstantlastModifiedInstant(java.nio.file.Path path)static voidmkdir(java.io.File d)Creates the directory named by this abstract pathname.static voidmkdir(java.io.File d, boolean skipExisting)Creates the directory named by this abstract pathname.static voidmkdirs(java.io.File d)Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.static voidmkdirs(java.io.File d, boolean skipExisting)Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.static java.io.Filenormalize(java.io.File file)NFC normalize a file (on Mac), otherwise do nothingstatic java.lang.Stringnormalize(java.lang.String name)On Mac: get NFC normalized form of given name, otherwise the given name.static java.lang.StringpathToString(java.io.File file)Convert a path to String, replacing separators as necessary.static java.lang.StringreadSymLink(java.io.File path)Read target path of the symlink.static java.lang.StringrelativizeGitPath(java.lang.String base, java.lang.String other)Expressesotheras a relative file path frombase.static java.lang.StringrelativizeNativePath(java.lang.String base, java.lang.String other)Expressesotheras a relative file path frombase.static java.lang.StringrelativizePath(java.lang.String base, java.lang.String other, java.lang.String dirSeparator, boolean caseSensitive)Expressesotheras a relative file path frombasestatic voidrename(java.io.File src, java.io.File dst)Rename a file or folder.static voidrename(java.io.File src, java.io.File dst, java.nio.file.CopyOption... options)Rename a file or folder using the passedCopyOptions.static voidsetHidden(java.io.File file, boolean hidden)Set a file hidden (on Windows)(package private) static voidsetLastModified(java.io.File file, long time)Deprecated.(package private) static voidsetLastModified(java.nio.file.Path path, java.time.Instant time)Set the last modified time of a file system object.static java.nio.file.PathtoPath(java.io.File f)Safe conversion fromFiletoPath.static voidtouch(java.nio.file.Path f)Touch the given file
-
-
-
Field Detail
-
LOG
private static final org.slf4j.Logger LOG
-
RNG
private static final java.util.Random RNG
-
NONE
public static final int NONE
Option to delete givenFile- See Also:
- Constant Field Values
-
RECURSIVE
public static final int RECURSIVE
Option to recursively delete givenFile- See Also:
- Constant Field Values
-
RETRY
public static final int RETRY
Option to retry deletion if not successful- See Also:
- Constant Field Values
-
SKIP_MISSING
public static final int SKIP_MISSING
Option to skip deletion if file doesn't exist- See Also:
- Constant Field Values
-
IGNORE_ERRORS
public static final int IGNORE_ERRORS
Option not to throw exceptions when a deletion finally doesn't succeed.- Since:
- 2.0
- See Also:
- Constant Field Values
-
EMPTY_DIRECTORIES_ONLY
public static final int EMPTY_DIRECTORIES_ONLY
Option to only delete empty directories. This option can be combined withRECURSIVE- Since:
- 3.0
- See Also:
- Constant Field Values
-
-
Method Detail
-
toPath
public static java.nio.file.Path toPath(java.io.File f) throws java.io.IOExceptionSafe conversion fromFiletoPath.- Parameters:
f-Fileto be converted toPath- Returns:
- the path represented by the file
- Throws:
java.io.IOException- in case the path represented by the file is not valid (InvalidPathException)- Since:
- 4.10
-
delete
public static void delete(java.io.File f) throws java.io.IOExceptionDelete file or empty folder- Parameters:
f-Fileto be deleted- Throws:
java.io.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
public static void delete(java.io.File f, int options) throws java.io.IOExceptionDelete 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:
java.io.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.
-
handleDeleteException
private static void handleDeleteException(java.io.File f, java.io.IOException e, int allOptions, int checkOptions) throws java.io.IOException- Throws:
java.io.IOException
-
rename
public static void rename(java.io.File src, java.io.File dst) throws java.io.IOExceptionRename 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:
java.io.IOException- if the rename has failed- Since:
- 3.0
- See Also:
FS.retryFailedLockFileCommit()
-
rename
public static void rename(java.io.File src, java.io.File dst, java.nio.file.CopyOption... options) throws java.nio.file.AtomicMoveNotSupportedException, java.io.IOExceptionRename 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:
java.nio.file.AtomicMoveNotSupportedException- if file cannot be moved as an atomic file system operationjava.io.IOException- Since:
- 4.1
-
mkdir
public static void mkdir(java.io.File d) throws java.io.IOExceptionCreates the directory named by this abstract pathname.- Parameters:
d- directory to be created- Throws:
java.io.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
public static void mkdir(java.io.File d, boolean skipExisting) throws java.io.IOExceptionCreates 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:
java.io.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
public static void mkdirs(java.io.File d) throws java.io.IOExceptionCreates 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:
java.io.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
public static void mkdirs(java.io.File d, boolean skipExisting) throws java.io.IOExceptionCreates 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:
java.io.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
public static void createNewFile(java.io.File f) throws java.io.IOExceptionAtomically 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:
java.io.IOException- if the named file already exists or if an I/O error occurred
-
createSymLink
public static java.nio.file.Path createSymLink(java.io.File path, java.lang.String target) throws java.io.IOExceptionCreate 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:
java.io.IOException- Since:
- 4.2
-
readSymLink
public static java.lang.String readSymLink(java.io.File path) throws java.io.IOExceptionRead target path of the symlink.- Parameters:
path- aFileobject.- Returns:
- target path of the symlink, or null if it is not a symbolic link
- Throws:
java.io.IOException- Since:
- 3.0
-
createTempDir
public static java.io.File createTempDir(java.lang.String prefix, java.lang.String suffix, java.io.File dir) throws java.io.IOExceptionCreate 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:
java.io.IOException- Since:
- 3.4
-
relativizeNativePath
public static java.lang.String relativizeNativePath(java.lang.String base, java.lang.String other)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
public static java.lang.String relativizeGitPath(java.lang.String base, java.lang.String other)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 java.lang.String relativizePath(java.lang.String base, java.lang.String other, java.lang.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
public static boolean isStaleFileHandle(java.io.IOException ioe)
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
public static boolean isStaleFileHandleInCausalChain(java.lang.Throwable throwable)
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
-
isSymlink
static boolean isSymlink(java.io.File file)
- Parameters:
file-- Returns:
trueif the passed file is a symbolic link
-
lastModified
@Deprecated static long lastModified(java.io.File file) throws java.io.IOExceptionDeprecated.uselastModifiedInstant(Path)instead which returns FileTime- Parameters:
file-- Returns:
- lastModified attribute for given file, not following symbolic links
- Throws:
java.io.IOException
-
lastModifiedInstant
static java.time.Instant lastModifiedInstant(java.nio.file.Path path)
- Parameters:
path-- Returns:
- lastModified attribute for given file, not following symbolic links
-
fileAttributes
static java.nio.file.attribute.BasicFileAttributes fileAttributes(java.io.File file) throws java.io.IOExceptionReturn all the attributes of a file, without following symbolic links.- Parameters:
file-- Returns:
BasicFileAttributesof the file- Throws:
java.io.IOException- in case of any I/O errors accessing the file- Since:
- 4.5.6
-
setLastModified
@Deprecated static void setLastModified(java.io.File file, long time) throws java.io.IOExceptionDeprecated.Set the last modified time of a file system object.- Parameters:
file-time-- Throws:
java.io.IOException
-
setLastModified
static void setLastModified(java.nio.file.Path path, java.time.Instant time) throws java.io.IOExceptionSet the last modified time of a file system object.- Parameters:
path-time-- Throws:
java.io.IOException
-
exists
static boolean exists(java.io.File file)
- Parameters:
file-- Returns:
trueif the given file exists, not following symbolic links
-
isHidden
static boolean isHidden(java.io.File file) throws java.io.IOException- Parameters:
file-- Returns:
trueif the given file is hidden- Throws:
java.io.IOException
-
setHidden
public static void setHidden(java.io.File file, boolean hidden) throws java.io.IOExceptionSet a file hidden (on Windows)- Parameters:
file- aFileobject.hidden- a boolean.- Throws:
java.io.IOException- Since:
- 4.1
-
getLength
public static long getLength(java.io.File file) throws java.io.IOExceptionGet file length- Parameters:
file- aFile.- Returns:
- length of the given file
- Throws:
java.io.IOException- Since:
- 4.1
-
isDirectory
static boolean isDirectory(java.io.File file)
- Parameters:
file-- Returns:
trueif the given file is a directory, not following symbolic links
-
isFile
static boolean isFile(java.io.File file)
- Parameters:
file-- Returns:
trueif the given file is a file, not following symbolic links
-
hasFiles
public static boolean hasFiles(java.nio.file.Path dir) throws java.io.IOExceptionWhether the path is a directory with files in it.- Parameters:
dir- directory path- Returns:
trueif the given directory path contains files- Throws:
java.io.IOException- on any I/O errors accessing the path- Since:
- 5.11
-
canExecute
public static boolean canExecute(java.io.File file)
Whether the given file can be executed.- Parameters:
file- aFileobject.- Returns:
trueif the given file can be executed.- Since:
- 4.1
-
getFileAttributesBasic
static FS.Attributes getFileAttributesBasic(FS fs, java.io.File file)
- Parameters:
fs-file-- Returns:
- non null attributes object
-
getFileAttributesPosix
public static FS.Attributes getFileAttributesPosix(FS fs, java.io.File file)
Get file system attributes for the given file.- Parameters:
fs- aFSobject.file- aFile.- Returns:
- file system attributes for the given file.
- Since:
- 4.1
-
normalize
public static java.io.File normalize(java.io.File file)
NFC normalize a file (on Mac), otherwise do nothing- Parameters:
file- aFile.- Returns:
- on Mac: NFC normalized
File, otherwise the passed file - Since:
- 4.1
-
normalize
public static java.lang.String normalize(java.lang.String name)
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
public static java.io.File canonicalize(java.io.File file)
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:
java.lang.SecurityException- ifFile.getCanonicalFile()throws one- Since:
- 4.2
-
pathToString
public static java.lang.String pathToString(java.io.File file)
Convert a path to String, replacing separators as necessary.- Parameters:
file- aFile.- Returns:
- file's path as a String
- Since:
- 4.10
-
touch
public static void touch(java.nio.file.Path f) throws java.io.IOExceptionTouch the given file- Parameters:
f- the file to touch- Throws:
java.io.IOException- 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
-
-