Top Description Inners Fields Constructors Methods
org.eclipse.jgit.util

public Class FileUtils

extends Object
Class Inheritance
Static Imports
java.nio.charset.StandardCharsets.UTF_8

File Utilities

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
FileUtils.IOFunction<
input type
A
,
output type
B
>

Like a java.util.function.Function but throwing an Exception.

Field Summary

Modifier and TypeField and Description
public static final int
EMPTY_DIRECTORIES_ONLY

Option to only delete empty directories.

public static final int
IGNORE_ERRORS

Option not to throw exceptions when a deletion finally doesn't succeed.

private static final Logger
public static final int
NONE

Option to delete given File

public static final int
RECURSIVE

Option to recursively delete given File

public static final int
RETRY

Option to retry deletion if not successful

private static final Random
public static final int
SKIP_MISSING

Option to skip deletion if file doesn't exist

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private static void
backOff(long delay, IOException cause)

public static boolean

Returns:

true if the given file can be executed.
canExecute
(File
a java.io.File object.
file
)

Whether the given file can be executed.

public static File

Returns:

canonicalized file, or the unchanged input file if canonicalization failed or if file == null
canonicalize
(File
to be canonicalized; may be null
file
)

Best-effort variation of java.io.File#getCanonicalFile() returning the input file if the file cannot be canonicalized instead of throwing java.io.IOException.

public static void
createNewFile(File
the file to be created
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.

public static File

Returns:

the temp dir created.
createTempDir
(String
prefix string
prefix
,
String
suffix string
suffix
,
File
The parent dir, can be null to use system default temp dir.
dir
)

Create a temporary directory.

public static long

Returns:

new amount of delay to wait before the next attempt.
delay
(long
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.
last
,
long
shortest amount of allowable delay between attempts.
min
,
long
longest amount of allowable delay between attempts.
max
)

Compute a delay in a min..max interval with random jitter.

public static void
delete(File
File to be deleted
f
)

Delete file or empty folder

public static void
delete(File
File to be deleted
f
,
int
deletion options, RECURSIVE for recursive deletion of a subtree, RETRY to retry when deletion failed. Retrying may help if the underlying file system doesn't allow deletion of files being read by another thread.
options
)

Delete file or folder

pack-priv static boolean

Returns:

true if the given file exists, not following symbolic links
exists
(File
the file
file
)

Whether the file exists

pack-priv static BasicFileAttributes

Returns:

BasicFileAttributes of the file
fileAttributes
(File
the file
file
)

Return all the attributes of a file, without following symbolic links.

pack-priv static FS.Attributes

Returns:

non null attributes object
getFileAttributesBasic
(FS fs, File
the file
file
)

Get basic file attributes

public static FS.Attributes

Returns:

file system attributes for the given file.
getFileAttributesPosix
(FS fs, File file)

Get file system attributes for the given file.

public static long

Returns:

length of the given file
getLength
(File file)

Get file length

private static void
handleDeleteException(File f, IOException e, int allOptions, int checkOptions)

public static boolean

Returns:

true if the given directory path contains files
hasFiles
(Path
directory path
dir
)

Whether the path is a directory with files in it.

pack-priv static boolean

Returns:

true if the given file is a directory, not following symbolic links
isDirectory
(File
the file
file
)

Check if file is directory

pack-priv static boolean

Returns:

true if the given file is a file, not following symbolic links
isFile
(File
the file
file
)

Check if File is a file

pack-priv static boolean

Returns:

true if the given file is hidden
isHidden
(File
the file
file
)

Check if file is hidden (on Windows)

public static boolean

Returns:

a boolean true if the IOException is a stale NFS file handle
isStaleFileHandle
(IOException ioe)

Determine if an IOException is a stale NFS file handle

public static boolean

Returns:

a boolean true if the throwable or a cause in its causal chain is a stale NFS file handle
isStaleFileHandleInCausalChain
(Throwable throwable)

Determine if a throwable or a cause in its causal chain is a stale NFS file handle

pack-priv static Instant

Returns:

lastModified attribute for given file, not following symbolic links
lastModifiedInstant
(Path
file path
path
)

Get last modified timestamp of a file

public static void
mkdir(File
directory to be created
d
)

Creates the directory named by this abstract pathname.

public static void
mkdir(File
directory to be created
d
,
boolean
if true skip creation of the given directory if it already exists in the file system
skipExisting
)

Creates the directory named by this abstract pathname.

public static void
mkdirs(File
directory to be created
d
)

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

public static void
mkdirs(File
directory to be created
d
,
boolean
if true skip creation of the given directory if it already exists in the file system
skipExisting
)

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

public static File

Returns:

on Mac: NFC normalized java.io.File, otherwise the passed file
normalize
(File file)

NFC normalize a file (on Mac), otherwise do nothing

public static String

Returns:

on Mac: NFC normalized form of given name
normalize
(String name)

On Mac: get NFC normalized form of given name, otherwise the given name.

public static String

Returns:

file's path as a String
pathToString
(File file)

Convert a path to String, replacing separators as necessary.

public static <
result type
T
>
T

Returns:

the result of the reader, or null if the file does not exist
readWithRetries
(File
to read
file
,
FileUtils.IOFunction<File, ? extends T>
for reading the file and creating an instance of T
reader
)

Invokes the given 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.

public static String

Returns:

Relative path from base to other
relativizeGitPath
(String
Base path
base
,
String
Destination path
other
)

Expresses other as a relative file path from base.

public static String

Returns:

Relative path from base to other
relativizeNativePath
(String
Base path
base
,
String
Destination path
other
)

Expresses other as a relative file path from base.

public static String

Returns:

A relative path that, when resolved against base, will yield the original other.
relativizePath
(String
The path against which other should be relativized. This will be assumed to denote the path to a folder and not a file.
base
,
String
The path that will be made relative to base.
other
,
String
A string that separates components of the path. In practice, this is "/" or "\\".
dirSeparator
,
boolean
Whether to consider differently-cased directory names as distinct
caseSensitive
)

Expresses other as a relative file path from base

For example, if called with the two following paths :

base = "c:\\Users\\jdoe\\eclipse\\git\\project"
other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"
public static void
rename(File
the old File
src
,
File
the new File
dst
)

Rename a file or folder.

public static void
rename(final File
the old file
src
,
final File
the new file
dst
,
CopyOption... options)

Rename a file or folder using the passed java.nio.file.CopyOptions.

public static void
setHidden(File
a java.io.File object.
file
,
boolean
a boolean.
hidden
)

Set a file hidden (on Windows)

pack-priv static void
setLastModified(Path
file path
path
,
Instant
last modified timestamp of the file
time
)

Set the last modified time of a file system object.

public static Path

Returns:

the path represented by the file
toPath
(File
File to be converted to Path
f
)

Safe conversion from java.io.File to java.nio.file.Path.

public static void
touch(Path
the file to touch
f
)

Touch the given file

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

EMPTY_DIRECTORIES_ONLYback to summary
public static final int EMPTY_DIRECTORIES_ONLY

Option to only delete empty directories. This option can be combined with RECURSIVE

Since
3.0
IGNORE_ERRORSback to summary
public static final int IGNORE_ERRORS

Option not to throw exceptions when a deletion finally doesn't succeed.

Since
2.0
LOGback to summary
private static final Logger LOG
NONEback to summary
public static final int NONE

Option to delete given File

RECURSIVEback to summary
public static final int RECURSIVE

Option to recursively delete given File

RETRYback to summary
public static final int RETRY

Option to retry deletion if not successful

RNGback to summary
private static final Random RNG
SKIP_MISSINGback to summary
public static final int SKIP_MISSING

Option to skip deletion if file doesn't exist

Constructor Detail

FileUtilsback to summary
public FileUtils()

Method Detail

backOffback to summary
private static void backOff(long delay, IOException cause) throws IOException
canExecuteback to summary
public static boolean canExecute(File file)

Whether the given file can be executed.

Parameters
file:File

a java.io.File object.

Returns:boolean

true if the given file can be executed.

Since
4.1
canonicalizeback to summary
public static File canonicalize(File file)

Best-effort variation of java.io.File#getCanonicalFile() returning the input file if the file cannot be canonicalized instead of throwing java.io.IOException.

Parameters
file:File

to be canonicalized; may be null

Returns:File

canonicalized file, or the unchanged input file if canonicalization failed or if file == null

Exceptions
SecurityException:
if java.io.File#getCanonicalFile() throws one
Since
4.2
createNewFileback to summary
public static void createNewFile(File f) throws IOException

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 java.nio.channels.FileLock facility should be used instead.

Parameters
f:File

the file to be created

Exceptions
IOException:
if the named file already exists or if an I/O error occurred
createTempDirback to summary
public static File createTempDir(String prefix, String suffix, File dir) throws IOException

Create a temporary directory.

Parameters
prefix:String

prefix string

suffix:String

suffix string

dir:File

The parent dir, can be null to use system default temp dir.

Returns:File

the temp dir created.

Exceptions
IOException:
if an IO error occurred
Since
3.4
delayback to summary
public static long delay(long last, long min, long max)

Compute a delay in a min..max interval with random jitter.

Parameters
last:long

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:long

shortest amount of allowable delay between attempts.

max:long

longest amount of allowable delay between attempts.

Returns:long

new amount of delay to wait before the next attempt.

Since
5.6
deleteback to summary
public static void delete(File f) throws IOException

Delete file or empty folder

Parameters
f:File

File to be deleted

Exceptions
IOException:
if deletion of f fails. This may occur if f didn'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.
deleteback to summary
public static void delete(File f, int options) throws IOException

Delete file or folder

Parameters
f:File

File to be deleted

options:int

deletion options, RECURSIVE for recursive deletion of a subtree, RETRY to retry when deletion failed. Retrying may help if the underlying file system doesn't allow deletion of files being read by another thread.

Exceptions
IOException:
if deletion of f fails. This may occur if f didn'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.
existsback to summary
pack-priv static boolean exists(File file)

Whether the file exists

Parameters
file:File

the file

Returns:boolean

true if the given file exists, not following symbolic links

fileAttributesback to summary
pack-priv static BasicFileAttributes fileAttributes(File file) throws IOException

Return all the attributes of a file, without following symbolic links.

Parameters
file:File

the file

Returns:BasicFileAttributes

BasicFileAttributes of the file

Exceptions
IOException:
in case of any I/O errors accessing the file
Since
4.5.6
getFileAttributesBasicback to summary
pack-priv static FS.Attributes getFileAttributesBasic(FS fs, File file)

Get basic file attributes

Parameters
fs:FS

a org.eclipse.jgit.util.FS object.

file:File

the file

Returns:FS.Attributes

non null attributes object

getFileAttributesPosixback to summary
public static FS.Attributes getFileAttributesPosix(FS fs, File file)

Get file system attributes for the given file.

Parameters
fs:FS

a org.eclipse.jgit.util.FS object.

file:File

a java.io.File.

Returns:FS.Attributes

file system attributes for the given file.

Since
4.1
getLengthback to summary
public static long getLength(File file) throws IOException

Get file length

Parameters
file:File

a java.io.File.

Returns:long

length of the given file

Exceptions
IOException:
if an IO error occurred
Since
4.1
handleDeleteExceptionback to summary
private static void handleDeleteException(File f, IOException e, int allOptions, int checkOptions) throws IOException
hasFilesback to summary
public static boolean hasFiles(Path dir) throws IOException

Whether the path is a directory with files in it.

Parameters
dir:Path

directory path

Returns:boolean

true if the given directory path contains files

Exceptions
IOException:
on any I/O errors accessing the path
Since
5.11
isDirectoryback to summary
pack-priv static boolean isDirectory(File file)

Check if file is directory

Parameters
file:File

the file

Returns:boolean

true if the given file is a directory, not following symbolic links

isFileback to summary
pack-priv static boolean isFile(File file)

Check if File is a file

Parameters
file:File

the file

Returns:boolean

true if the given file is a file, not following symbolic links

isHiddenback to summary
pack-priv static boolean isHidden(File file) throws IOException

Check if file is hidden (on Windows)

Parameters
file:File

the file

Returns:boolean

true if the given file is hidden

Exceptions
IOException:
if an IO error occurred
isStaleFileHandleback to summary
public static boolean isStaleFileHandle(IOException ioe)

Determine if an IOException is a stale NFS file handle

Parameters
ioe:IOException

an java.io.IOException object.

Returns:boolean

a boolean true if the IOException is a stale NFS file handle

Since
4.1
isStaleFileHandleInCausalChainback to summary
public static boolean isStaleFileHandleInCausalChain(Throwable throwable)

Determine if a throwable or a cause in its causal chain is a stale NFS file handle

Parameters
throwable:Throwable

a java.lang.Throwable object.

Returns:boolean

a boolean true if the throwable or a cause in its causal chain is a stale NFS file handle

Since
4.7
lastModifiedInstantback to summary
pack-priv static Instant lastModifiedInstant(Path path)

Get last modified timestamp of a file

Parameters
path:Path

file path

Returns:Instant

lastModified attribute for given file, not following symbolic links

mkdirback to summary
public static void mkdir(File d) throws IOException

Creates the directory named by this abstract pathname.

Parameters
d:File

directory to be created

Exceptions
IOException:
if creation of d fails. This may occur if d did 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.
mkdirback to summary
public static void mkdir(File d, boolean skipExisting) throws IOException

Creates the directory named by this abstract pathname.

Parameters
d:File

directory to be created

skipExisting:boolean

if true skip creation of the given directory if it already exists in the file system

Exceptions
IOException:
if creation of d fails. This may occur if d did 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.
mkdirsback to summary
public static void mkdirs(File d) throws IOException

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:File

directory to be created

Exceptions
IOException:
if creation of d fails. This may occur if d did 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.
mkdirsback to summary
public static void mkdirs(File d, boolean skipExisting) throws IOException

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:File

directory to be created

skipExisting:boolean

if true skip creation of the given directory if it already exists in the file system

Exceptions
IOException:
if creation of d fails. This may occur if d did 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.
normalizeback to summary
public static File normalize(File file)

NFC normalize a file (on Mac), otherwise do nothing

Parameters
file:File

a java.io.File.

Returns:File

on Mac: NFC normalized java.io.File, otherwise the passed file

Since
4.1
normalizeback to summary
public static String normalize(String name)

On Mac: get NFC normalized form of given name, otherwise the given name.

Parameters
name:String

a java.lang.String object.

Returns:String

on Mac: NFC normalized form of given name

Since
4.1
pathToStringback to summary
public static String pathToString(File file)

Convert a path to String, replacing separators as necessary.

Parameters
file:File

a java.io.File.

Returns:String

file's path as a String

Since
4.10
readWithRetriesback to summary
public static <T> T readWithRetries(File file, FileUtils.IOFunction<File, ? extends T> reader) throws Exception

Invokes the given 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.

Parameters
<T>
result type
file:File

to read

reader:FileUtils.IOFunction<File, ? extends T>

for reading the file and creating an instance of T

Returns:T

the result of the reader, or null if the file does not exist

Exceptions
Exception:
if a problem occurs
Since
6.2
relativizeGitPathback to summary
public static String relativizeGitPath(String base, String other)

Expresses other as a relative file path from base. File-separator and case sensitivity are based on Git's internal representation of files (which matches Unix). See also org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean).

Parameters
base:String

Base path

other:String

Destination path

Returns:String

Relative path from base to other

Since
4.8
relativizeNativePathback to summary
public static String relativizeNativePath(String base, String other)

Expresses other as a relative file path from base. File-separator and case sensitivity are based on the current file system. See also org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean).

Parameters
base:String

Base path

other:String

Destination path

Returns:String

Relative path from base to other

Since
4.8
relativizePathback to summary
public static String relativizePath(String base, String other, String dirSeparator, boolean caseSensitive)

Expresses other as a relative file path from base

For example, if called with the two following paths :

base = "c:\\Users\\jdoe\\eclipse\\git\\project"
other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"
This will return "..\\another_project\\pom.xml".

Note

that this will return the empty String if base and other are equal.

Parameters
base:String

The path against which other should be relativized. This will be assumed to denote the path to a folder and not a file.

other:String

The path that will be made relative to base.

dirSeparator:String

A string that separates components of the path. In practice, this is "/" or "\\".

caseSensitive:boolean

Whether to consider differently-cased directory names as distinct

Returns:String

A relative path that, when resolved against base, will yield the original other.

Since
4.8
renameback to summary
public static void rename(File src, File dst) throws IOException

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:File

the old File

dst:File

the new File

Exceptions
IOException:
if the rename has failed
Since
3.0
See Also
FS#retryFailedLockFileCommit()
renameback to summary
public static void rename(final File src, final File dst, CopyOption... options) throws AtomicMoveNotSupportedException, IOException

Rename a file or folder using the passed java.nio.file.CopyOptions. 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 if java.nio.file.StandardCopyOption#REPLACE_EXISTING has been set. If java.nio.file.StandardCopyOption#ATOMIC_MOVE has been set the rename will be done atomically or fail with an java.nio.file.AtomicMoveNotSupportedException

Parameters
src:File

the old file

dst:File

the new file

options:CopyOption[]

options to pass to java.nio.file.Files#move(java.nio.file.Path, java.nio.file.Path, CopyOption...)

Exceptions
AtomicMoveNotSupportedException:
if file cannot be moved as an atomic file system operation
IOException:
if an IO error occurred
Since
4.1
setHiddenback to summary
public static void setHidden(File file, boolean hidden) throws IOException

Set a file hidden (on Windows)

Parameters
file:File

a java.io.File object.

hidden:boolean

a boolean.

Exceptions
IOException:
if an IO error occurred
Since
4.1
setLastModifiedback to summary
pack-priv static void setLastModified(Path path, Instant time) throws IOException

Set the last modified time of a file system object.

Parameters
path:Path

file path

time:Instant

last modified timestamp of the file

Exceptions
IOException:
if an IO error occurred
toPathback to summary
public static Path toPath(File f) throws IOException

Safe conversion from java.io.File to java.nio.file.Path.

Parameters
f:File

File to be converted to Path

Returns:Path

the path represented by the file

Exceptions
IOException:
in case the path represented by the file is not valid ( java.nio.file.InvalidPathException)
Since
4.10
touchback to summary
public static void touch(Path f) throws IOException

Touch the given file

Parameters
f:Path

the file to touch

Exceptions
IOException:
if an IO error occurred
Since
5.1.8
org.eclipse.jgit.util back to summary

public Interface FileUtils.IOFunction<A, B>

Annotations
@FunctionalInterface
Type Parameters
<A>
input type
<B>
output type

Like a java.util.function.Function but throwing an Exception.
Since
6.2

Method Summary

Modifier and TypeMethod and Description
public B

Returns:

the output
apply
(A
input to operate on
t
)

Performs the function.

Method Detail

applyback to summary
public B apply(A t) throws Exception

Performs the function.

Parameters
t:A

input to operate on

Returns:B

the output

Exceptions
Exception:
if a problem occurs