Class FileUtil
- java.lang.Object
-
- com.intellij.openapi.util.io.FileUtil
-
- jetbrains.buildServer.util.FileUtil
-
public class FileUtil extends FileUtil
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
FileUtil.DeleteState
static interface
FileUtil.ErrorReporter
Used to report file operation errors to some logstatic interface
FileUtil.FilesDeleteListener
static interface
FileUtil.IOAction
static interface
FileUtil.Processor
static class
FileUtil.RegexFileFilter
File filter that accepts files with the name specified by a regular expression.
-
Field Summary
Fields Modifier and Type Field Description static FileFilter
ACCEPT_ALL_FILES_FILTER
static String
DIST_SUFFIX
-
Constructor Summary
Constructors Constructor Description FileUtil()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static boolean
areTheSame(File file1, File file2)
Checks that both file pointers specify the same object.static void
atomicRename(File from, File to, int maxAttempts)
Renames (moves) thefrom
file to theto
file, replacing the second one if exists.static boolean
checkContentEqual(File file1, File file2)
Check both files exist and are same byte-by-byte.static void
checkTmpDir()
Checks if it is allowed to use tmpDir taken from "java.io.tmpdir" system propertystatic void
close(Closeable e)
Closes a resource if it is not null All possible IOExceptions are ignoredstatic void
close(ZipFile e)
Closes a resource if it is not null All possible IOExceptions are ignoredstatic void
closeAll(Closeable... toClose)
Closes all not-null resources All possible IOExceptions are ignoredstatic String
convertAntToRegexp(String antPattern)
static String
convertAntToRegexp(String antPattern, boolean ignoreStartingSlash)
static void
copy(File from, File to)
static void
copy(InputStream from, File to)
static void
copy(InputStream is, OutputStream os)
Same as copyStream.static void
copyFilePart(File sourceFile, long offset, long length, OutputStream destination)
Copies a part of a file to output stream.static void
copyFromResourcesIfNotExist(Path appConfFolder, String fileInResources)
static void
copyResource(Class<?> clazz, String resourceName, File outputFile)
Copies contents of the specified resource into the specified file.static void
copyResource(String resourceName, File outputFile)
Deprecated.UsecopyResource(Class, String, java.io.File)
to overcome classloader change issuesstatic void
copyResourceIfNotExists(Class<?> clazz, String resourceName, File outputFile)
Copies the resource file into specified file if it doesn't exist (seecopyResource(Class, String, java.io.File)
).static void
copyResourceWithDist(Class<?> clazz, String resourceName, File outputFile)
Copies the resource file into specified file (seecopyResource(Class, String, java.io.File)
).static void
copyStreamRangeAndClose(InputStream source, long offset, long length, OutputStream destination)
Copies a stream range of a file to output stream.static void
copyStreams(InputStream is, OutputStream os)
static File
createDir(File dir)
Creates directory if it does not exist.static File
createEmptyDir(File dir)
Creates an empty directory, removing all content if it already exists.static boolean
createSymlink(File target, File symlinkFile)
Attempts to create a symlink atsymlinkFile
that points totarget
static File
createTempDirectory(String prefix, String suffix)
Overrides the same method fromFileUtil
.static File
createTempDirectory(String prefix, String suffix, File in)
static File
createTempFile(File dir, String prefix, String suffix, boolean create)
Overrides the same method fromFileUtil
.static File
createTempFile(String prefix, String suffix)
Overrides the same method fromFileUtil
.static boolean
delete(File file)
Removes specified file or directory, same as FileUtil.delete(file, 10).static Set<File>
delete(File fileOrDirectory, int numAttempts)
Removes specified directory or file, for each removed file performs operation up to numAttempts.static Set<File>
delete(File fileOrDirectory, FileFilter fileFilter, int numAttempts)
Removes specified directory or file, for each removed file performs operation up to numAttemptsstatic Set<File>
delete(File fileOrDirectory, FileFilter fileFilter, int numAttempts, FileUtil.FilesDeleteListener deleteListener)
Removes files infileOrDirectory
, skipping all files that do not matchfileFilter
as well as all their subtitles/subfolders iffileFilter
is a directory.static boolean
deleteDirNative(File dir)
Deletes dir using native command rd for windows and rm for *nixstatic Collection<File>
deleteFiles(Collection<File> filesToDelete)
Deletes the given files, in several attempts, if needed.static boolean
deleteIfEmpty(File dir)
Removes directory if it is emptystatic File
findFile(FileFilter filter, File... directories)
Searches for a file in the specified directories recursively.static Collection<File>
findFiles(FileFilter filter, File... directories)
Searches for files in the specified directories recursively.static String
fixDirectoryName(String name)
Fixes directory name: replaces all dangerous characters with '_'.static String
fixDirectoryNameAllowUnicode(String name)
Fixes directory name in relaxed manner.static long
freeSpaceKb(String path)
static File
getCanonicalFile(File file)
Attempts to obtain canonical file from the specified file and if it fails returns absolute file.static String
getCommonParent(String firstUrl, String secondUrl)
Deprecated.static File
getCommonParentFile(File file1, File file2)
static String
getExtension(String fileNameWithDirectory)
Unlike com.intellij.openapi.util.io.FileUtil.getExtension, can use this with full file name (including directory name).static File
getFileInSameDir(File origFile, String neededFileName)
Returns a java.io.File object representing the file located in the same directory as origFile with the given file name
assert getFileInSameDir(new File("somDir/someFile.txt"), "anotherFile.txt"). equals(new File("someDir/anotherFile.txt"));
static String
getFilesSignature(Collection<File> fileCollection)
static Long
getFreeSpace(File file)
Computes free space on the disk that contains a filestatic Long
getFreeSpaceBytesSafe(File dir)
Gets free space in bytes avoidingLong
overflow if free space exceeds 2^63 bytesstatic Long
getFreeSpaceKB(File dir)
Deprecated.since 10.0.static String
getName(String path)
Gets name of the file in platform-independent way (unlike new File(path).getName()) For directories, gets name of the directorystatic String
getNameOrAbsolutePath(File baseDir, File checkDir)
Checks whether directory lies directly under baseDir.static String
getNameWithoutExtension(File file)
static String
getNameWithoutExtension(String name)
static List<File>
getSubDirectories(File root)
static String
getTempDirectory()
Overrides the same method fromFileUtil
.static long
getTotalDirectorySize(File dir)
Returns the directory size in bytes of files under the specified directory (non recursive).static long
getTotalDirectorySize(File dir, boolean recursively)
Returns the directory size in bytes of files under the specified directory recursively.static Reader
getUTF8Reader(File file)
Returns Reader with utf-8 encoding to read the file, because FileReader uses default platform encodingstatic boolean
haveEqualContentIgnoringLineEndings(File file1, File file2)
Check both files exist and have same content ignoring line-endings and leading/trailing spaces.static boolean
isAncestor(File ancestor, File file, boolean strict)
Check if theancestor
is an ancestor offile
.static boolean
isBadDirectoryName(String name)
Checks whether specified name contains dangerous characters which might prevent successful directory creation.static boolean
isBinaryData(byte[] data, int size)
Returns whether specified byte array represents binary data (not text)static boolean
isBinaryFile(File file)
Returns whether a specifiedfile
is a binary file.static boolean
isEmptyDir(File dir)
Returns true if directory is empty or does not exist and false otherwise.static boolean
isFileSeparator(char c1)
static boolean
isReadonly(File file)
Returns true if file is readonly and false otherwisestatic boolean
isSymlink(File file)
Checks whetherfile
is a symlink by resolving absolute path into real (canonical) onestatic boolean
isTextData(byte[] data, int size)
Returns whether specified byte array represents text data (not binary)static File[]
listFiles(File directory)
A simple wrapper aroundfile.listFiles(filter)
that handles possiblenull
result.static File[]
listFiles(File directory, FilenameFilter filter)
A simple wrapper aroundfile.listFiles(filter)
that handles possiblenull
result.static <C extends Collection<String>>
ClistFilesRecursively(File dir, String prefix, boolean includeDirs, int depthLimit, Predicate<File> predicate, C collection)
Traverses the given directory and retrieves all files (and nested directories, if specified).static boolean
moveDirWithContent(File fromDir, File to, FileUtil.ErrorReporter reporter)
Move directory content from given directory to target location.static String
normalizeAbsolutePath(String path)
Normalizes absolute path by eliminating all possible path/../ /./ ./path combinations.static String
normalizeRelativePath(String path)
Normalizes relative path by eliminating all possible path/../ /./ ./path combinations Doesn't check if the provided path is relative, but may return unexpected result for absolute paths.static String
normalizeSeparator(String filePath)
Replace all separators like / and \ to File.separatorCharstatic org.jdom.Element
parseDocument(File file)
static org.jdom.Element
parseDocument(File file, boolean validate)
static org.jdom.Element
parseDocument(InputStream input, boolean validate)
static org.jdom.Element
parseDocument(Reader input, boolean validate)
static void
processXmlFile(File file, FileUtil.Processor processor)
Updates the file according to the provided processor.static List<String>
readFile(File file)
Read list of lines from the file.static List<String>
readFile(File file, String encoding)
Read list of lines from the file.static String
readResourceAsString(Class<?> clazz, String resourceName, Charset charset)
Reads the jar resource as a text.static String
readText(File file)
Read the specified text file into a String variable.static String
readText(File file, String encoding)
Read the specified text file into a String variable.static void
readXmlFile(File file, FileUtil.Processor p)
static boolean
rename(File from, File to, FileUtil.ErrorReporter reporter)
Rename/move file or directory to target location .static void
renameAndReportErrors(File oldName, File newName)
Renames or moves the give file or directory.static File
renameFileNameOnly(File file, String newName)
static File
resolvePath(File baseDir, String path)
If path is absolute, returns path, otherwise it returns path within specified base directory.static boolean
sameButDifferInCase(File file1, File file2)
Check whether the two given paths denotes the same file but in differ cases.static void
saveDocument(org.jdom.Document document, File file)
static void
setExectuableAttribute(String path, boolean executableFlag)
Set executable attribute, it makes sense only on non-windows platforms.static void
sortFiles(File[] files)
static void
symlinkAwareDelete(File fileOrDirectory)
Deprecated.usedelete(File)
static void
symlinkAwareDelete(File fileOrDirectory, FileFilter fileFilter, int numAttempts)
Deprecated.static void
writeFile(File file, String text)
Deprecated.This procedure loses exceptions that is very dangerous.static void
writeFile(File file, String text, String encoding)
Writes text to file.static void
writeFile(File file, String text, Charset charset)
Creates the file with the parental directories if need and writes the text to the file.static void
writeFileAndReportErrors(File file, String text)
Writes text to file.static void
writeViaTmpFile(File targetFile, InputStream content, FileUtil.IOAction beforeWriteAction)
Utility to reliably save a file not leaving the file in a corrupted state in case of disk errors or process crash.-
Methods inherited from class com.intellij.openapi.util.io.FileUtil
adaptiveLoadBytes, adaptiveLoadText, asyncDelete, asyncDelete, canCallCanExecute, canExecute, collectMatchedFiles, comparePaths, copy, copyContent, copyDir, copyDir, copyDir, createIfDoesntExist, createParentDirs, createSequentFileName, ensureCanCreateFile, findFirstThatExist, findSequentNonexistentFile, getParentFile, getRelativePath, getRelativePath, getRelativePath, isAbsolute, isFilePathAcceptable, loadBytes, loadBytes, loadFileBytes, loadFileText, loadFileText, loadText, loadTextAndClose, moveDirWithContent, nameToCompare, normalizePath, pathHashCode, pathsEqual, processFilesRecursively, rename, resolveShortWindowsName, sanitizeFileName, setReadOnlyAttribute, startsWith, startsWith, toSystemDependentName, toSystemIndependentName, unquote, writeToFile, writeToFile
-
-
-
-
Field Detail
-
ACCEPT_ALL_FILES_FILTER
public static final FileFilter ACCEPT_ALL_FILES_FILTER
-
DIST_SUFFIX
public static final String DIST_SUFFIX
- See Also:
- Constant Field Values
-
-
Method Detail
-
readFile
@NotNull public static List<String> readFile(@NotNull File file) throws IOException
Read list of lines from the file. Each line is terminated by corresponding line feed- Parameters:
file
- file to read- Returns:
- list of file lines
- Throws:
IOException
- upon a problem when reading from file- Since:
- 4.0.1
-
readFile
@NotNull public static List<String> readFile(@NotNull File file, @NotNull String encoding) throws IOException
Read list of lines from the file. Each line is terminated by corresponding line feed- Parameters:
file
- file to read- Returns:
- list of file lines
- Throws:
IOException
- upon a problem when reading from file- Since:
- 9.0
-
readText
@NotNull public static String readText(@NotNull File file) throws IOException
Read the specified text file into a String variable.- Parameters:
file
- file to read- Returns:
- file text
- Throws:
IOException
- upon a problem when reading from file- Since:
- 5.0
-
readText
@NotNull public static String readText(@NotNull File file, @NotNull String encoding) throws IOException
Read the specified text file into a String variable.- Parameters:
file
- file to readencoding
- encoding- Returns:
- file text
- Throws:
IOException
- upon a problem when reading from file- Since:
- 7.1
-
writeFile
@Deprecated public static void writeFile(@NotNull File file, @NotNull String text)
Deprecated.This procedure loses exceptions that is very dangerous. UsewriteFileAndReportErrors(java.io.File, java.lang.String)
instead.TODO rename it to writeFileWithNoExceptions Write text to file and report any errors via LOG.error()- Parameters:
file
- file to writetext
- text to write to file
-
writeFileAndReportErrors
public static void writeFileAndReportErrors(@NotNull File file, @NotNull String text) throws IOException
Writes text to file. Throws IO exception if error occurred.- Parameters:
file
- file to write text totext
- text to write in file- Throws:
IOException
- if error occurred- Since:
- 6.5
-
writeFile
public static void writeFile(@NotNull File file, @NotNull String text, @NotNull Charset charset) throws IOException
Creates the file with the parental directories if need and writes the text to the file. Throws IO exception if an error occurred.- Parameters:
file
- file to write text totext
- text to write in the filecharset
- encoding (seeStandardCharsets
)- Throws:
IOException
- if an error occurred- Since:
- 2020.2
-
writeFile
public static void writeFile(@NotNull File file, @NotNull String text, @NotNull String encoding) throws IOException
Writes text to file. Throws IO exception if error occurred.- Parameters:
file
- file to write text totext
- text to write in fileencoding
- encoding- Throws:
IOException
- if error occurred- Since:
- 7.1
-
readXmlFile
public static void readXmlFile(@NotNull File file, @NotNull FileUtil.Processor p)
-
parseDocument
@NotNull public static org.jdom.Element parseDocument(@NotNull File file) throws org.jdom.JDOMException, IOException
- Throws:
org.jdom.JDOMException
IOException
-
parseDocument
@NotNull public static org.jdom.Element parseDocument(@NotNull File file, boolean validate) throws org.jdom.JDOMException, IOException
- Throws:
org.jdom.JDOMException
IOException
-
parseDocument
@NotNull public static org.jdom.Element parseDocument(@NotNull InputStream input, boolean validate) throws org.jdom.JDOMException, IOException
- Throws:
org.jdom.JDOMException
IOException
-
parseDocument
@NotNull public static org.jdom.Element parseDocument(@NotNull Reader input, boolean validate) throws org.jdom.JDOMException, IOException
- Throws:
org.jdom.JDOMException
IOException
- Since:
- 8.0
-
processXmlFile
public static void processXmlFile(@NotNull File file, @NotNull FileUtil.Processor processor)
Updates the file according to the provided processor.
-
saveDocument
public static void saveDocument(@NotNull org.jdom.Document document, @NotNull File file) throws IOException
- Throws:
IOException
-
getFilesSignature
@NotNull public static String getFilesSignature(@NotNull Collection<File> fileCollection)
-
createTempDirectory
@NotNull public static File createTempDirectory(@NotNull String prefix, String suffix, File in) throws IOException
- Throws:
IOException
-
createTempDirectory
@NotNull public static File createTempDirectory(@NonNls String prefix, @NonNls String suffix) throws IOException
Overrides the same method fromFileUtil
.- Throws:
IOException
-
createTempFile
@NotNull public static File createTempFile(@NonNls File dir, @NonNls @NotNull String prefix, @NonNls String suffix, boolean create) throws IOException
Overrides the same method fromFileUtil
.- Throws:
IOException
-
createTempFile
@NotNull public static File createTempFile(@NonNls @NotNull String prefix, @NonNls String suffix) throws IOException
Overrides the same method fromFileUtil
.- Throws:
IOException
-
getTempDirectory
@NotNull public static String getTempDirectory()
Overrides the same method fromFileUtil
.
-
getFileInSameDir
@NotNull public static File getFileInSameDir(@NotNull File origFile, String neededFileName)
Returns a java.io.File object representing the file located in the same directory as origFile with the given file name
assert getFileInSameDir(new File("somDir/someFile.txt"), "anotherFile.txt"). equals(new File("someDir/anotherFile.txt"));
- Parameters:
origFile
- original fileneededFileName
- name of required file- Returns:
- required file
-
moveDirWithContent
public static boolean moveDirWithContent(File fromDir, File to, FileUtil.ErrorReporter reporter)
Move directory content from given directory to target location. If there is a problem moving a file, a error is reported via ErrorReporter. Does not override existing target files.- Parameters:
fromDir
- source directoryto
- target directoryreporter
- used to report text errors during the move- Returns:
- true if
fromDir
was moved toto
path, false if there were some errors during the move - Since:
- 9.0
-
rename
public static boolean rename(@NotNull File from, @NotNull File to, @Nullable FileUtil.ErrorReporter reporter)
Rename/move file or directory to target location . If there is a problem moving a file, a error is reported via ErrorReporter. If simple rename of a file doesn't work, tries to rename via copy + deleteDoes not override existing target files.
- Parameters:
from
- source file or directoryto
- target file or directoryreporter
- used to report text errors during the move; i.e. if move is not successful, reports a error message.- Returns:
- true if rename/move was successful, false otherwise
- Since:
- 9.0
-
writeViaTmpFile
public static void writeViaTmpFile(@NotNull File targetFile, @NotNull InputStream content, @NotNull FileUtil.IOAction beforeWriteAction) throws IOException
Utility to reliably save a file not leaving the file in a corrupted state in case of disk errors or process crash. Writes provided content to the temporary targetFile.new file, closes the input stream, calls provided action, and renames tmp file to the targetFile. Action can be used to make backup copies of the targetFile- Parameters:
targetFile
- target filecontent
- content to write, the stream will be closed after writingbeforeWriteAction
- action to run before renaming temp file to the targetFile- Throws:
IOException
- in case of IO error- Since:
- 2018.1
-
atomicRename
public static void atomicRename(@NotNull File from, @NotNull File to, int maxAttempts) throws IOException
Renames (moves) thefrom
file to theto
file, replacing the second one if exists.- Throws:
IOException
-
copyFromResourcesIfNotExist
public static void copyFromResourcesIfNotExist(Path appConfFolder, String fileInResources)
-
renameAndReportErrors
public static void renameAndReportErrors(@NotNull File oldName, @NotNull File newName) throws IOException, SecurityException
Renames or moves the give file or directory.Performs
File.renameTo(java.io.File)
but checks the result and throwsIOException
when the rename is unsuccessful.- Parameters:
oldName
- old path and name.newName
- new path and name.- Throws:
IOException
- when rename is unsuccessful.SecurityException
- if a security manager exists and it has denied the operation.- Since:
- 8.0
-
sameButDifferInCase
public static boolean sameButDifferInCase(@NotNull File file1, @NotNull File file2)
Check whether the two given paths denotes the same file but in differ cases.Note: the result is depend on the actual file system. In unix this function always returns false.
- Parameters:
file1
- the first file to compare.file2
- the second file to compare.- Returns:
- differ but in case only.
- Since:
- 8.0
-
renameFileNameOnly
@NotNull public static File renameFileNameOnly(@NotNull File file, @NotNull String newName) throws IOException, SecurityException
- Throws:
IOException
SecurityException
-
resolvePath
@NotNull public static File resolvePath(@NotNull File baseDir, @NotNull String path)
If path is absolute, returns path, otherwise it returns path within specified base directory.- Parameters:
baseDir
- base directory for the resolving the pathpath
- path to be resolved, may be absolute or relative for baseDir- Returns:
- absolute path File
-
copyResource
@Deprecated public static void copyResource(@NotNull String resourceName, @NotNull File outputFile)
Deprecated.UsecopyResource(Class, String, java.io.File)
to overcome classloader change issuesCopies contents of the specified resource into the specified file.- Parameters:
resourceName
- Name of the classpath resourceoutputFile
- target file for the resource data
-
copyResource
public static void copyResource(@NotNull Class<?> clazz, @NotNull String resourceName, @NotNull File outputFile)
Copies contents of the specified resource into the specified file. UsesClass.getResourceAsStream(String)
in 'clazz' parameter to fetch the resource. NOTE: File will be created even if there was no such resource- Parameters:
clazz
- class from the class loader that can access the resourceresourceName
- Name of the classpath resourceoutputFile
- target file for the resource data
-
copyResourceIfNotExists
public static void copyResourceIfNotExists(@NotNull Class<?> clazz, @NotNull String resourceName, @NotNull File outputFile)
Copies the resource file into specified file if it doesn't exist (seecopyResource(Class, String, java.io.File)
).- Parameters:
clazz
- class from the class loader that can access the resourceresourceName
- the name of the classpath resourceoutputFile
- destination file for the resource data
-
copyResourceWithDist
public static void copyResourceWithDist(@NotNull Class<?> clazz, @NotNull String resourceName, @NotNull File outputFile)
Copies the resource file into specified file (seecopyResource(Class, String, java.io.File)
).Handles the '.dist' file as well, i.e.:
- if the destination file has been changed (if it does not equal to the '.dist' file), only the '.dist' file is copied (thus the destination file is not overwritten);
- if the destination file has not been changed, or does not exist or the '.dist' file does not exist, both files are copied.
- Parameters:
clazz
- class from the class loader that can access the resourceresourceName
- the name of the classpath resourceoutputFile
- destination file for the resource data
-
readResourceAsString
@Nullable public static String readResourceAsString(@NotNull Class<?> clazz, @NotNull String resourceName, @NotNull Charset charset) throws IOException
Reads the jar resource as a text.- Parameters:
clazz
- class (used to determine the resource path).resourceName
- name of resource to read.charset
- character set of the resource file.- Returns:
- text from resource, or null if the resource not found.
- Throws:
IOException
- when IO error occurs- Since:
- 6.0
-
copyStreams
public static void copyStreams(@NotNull InputStream is, @NotNull OutputStream os) throws IOException
- Throws:
IOException
-
copyFilePart
public static void copyFilePart(@NotNull File sourceFile, long offset, long length, @NotNull OutputStream destination) throws IOException
Copies a part of a file to output stream. Stream is closed after part was copied.- Parameters:
sourceFile
- file to copyoffset
- file offsetlength
- length of datadestination
- stream to write to- Throws:
IOException
- if IOException exception occurs
-
copyStreamRangeAndClose
public static void copyStreamRangeAndClose(@NotNull InputStream source, long offset, long length, @NotNull OutputStream destination) throws IOException
Copies a stream range of a file to output stream. Stream would be closed at end- Parameters:
source
- file to copyoffset
- file offsetlength
- length of datadestination
- stream to write to- Throws:
IOException
- if IOException exception occurs- Since:
- 6.5
- See Also:
TCStreamUtil.skip(java.io.InputStream, long)
,TCStreamUtil.writeBinary(java.io.InputStream, long, java.io.OutputStream)
-
close
public static void close(@Nullable Closeable e)
Closes a resource if it is not null All possible IOExceptions are ignored- Parameters:
e
- resource to close
-
close
public static void close(@Nullable ZipFile e)
Closes a resource if it is not null All possible IOExceptions are ignored- Parameters:
e
- resource to close- Since:
- 8.0
-
closeAll
public static void closeAll(@NotNull Closeable... toClose)
Closes all not-null resources All possible IOExceptions are ignored- Parameters:
toClose
- resources to close- Since:
- 7.0
-
createDir
@NotNull public static File createDir(@NotNull File dir) throws IOException
Creates directory if it does not exist. ThrowsIOException
if directory creation was not successful.- Parameters:
dir
- directory to be created- Returns:
- dir
- Throws:
IOException
- if failed to create directory
-
createEmptyDir
@NotNull public static File createEmptyDir(@NotNull File dir) throws IOException
Creates an empty directory, removing all content if it already exists.- Parameters:
dir
- the directory to create- Returns:
- result file
- Throws:
IOException
- in case of I/O error occurred
-
getTotalDirectorySize
public static long getTotalDirectorySize(@Nullable File dir)
Returns the directory size in bytes of files under the specified directory (non recursive).- Parameters:
dir
- the directory to traverse- Returns:
- size in bytes
-
getTotalDirectorySize
public static long getTotalDirectorySize(@Nullable File dir, boolean recursively)
Returns the directory size in bytes of files under the specified directory recursively.- Parameters:
dir
- the directory to traverse- Returns:
- size in bytes
- Since:
- 7.1.4
-
deleteIfEmpty
public static boolean deleteIfEmpty(@NotNull File dir)
Removes directory if it is empty- Parameters:
dir
- directory to be removed- Returns:
- true if the directory was removed and false otherwise
-
delete
@NotNull public static Set<File> delete(@NotNull File fileOrDirectory, int numAttempts)
Removes specified directory or file, for each removed file performs operation up to numAttempts. If directory is provided, all files under this directory will be removed recursively.- Parameters:
fileOrDirectory
- file or directory to removenumAttempts
- maximum number of attempts to perform (must be positive)- Returns:
- set of successfully removed files
- Since:
- 8.0
-
symlinkAwareDelete
@Deprecated public static void symlinkAwareDelete(@NotNull File fileOrDirectory)
Deprecated.usedelete(File)
Removes specified directory or file. On Unix it doesn't remove contents of the symlink dir if it points outside of thefileOrDirectory
. On Windows no such checks are performed and this method behaves in the same way asdelete(java.io.File)
.- Parameters:
fileOrDirectory
- file or directory to remove- Since:
- 9.0
-
symlinkAwareDelete
@Deprecated public static void symlinkAwareDelete(@NotNull File fileOrDirectory, @NotNull FileFilter fileFilter, int numAttempts)
Deprecated.Removes specified directory or file, for each removed file performs operation up to numAttempts. On Unix it doesn't remove contents of the symlink dir if it points outside of thefileOrDirectory
. On Windows no such checks are performed and this method behaves in the same way asdelete(java.io.File, java.io.FileFilter, int)
.- Parameters:
fileOrDirectory
- file or directory to removenumAttempts
- maximum number of attempts to perform (must be positive)fileFilter
- filter for files, must return true for files to be removed and false otherwise- Since:
- 9.0
-
delete
@NotNull public static Set<File> delete(@NotNull File fileOrDirectory, @NotNull FileFilter fileFilter, int numAttempts)
Removes specified directory or file, for each removed file performs operation up to numAttempts- Parameters:
fileOrDirectory
- file or directory to removenumAttempts
- maximum number of attempts to perform (must be positive)fileFilter
- filter for files, must return true for files to be removed and false otherwise- Returns:
- set of successfully removed files
- Since:
- 8.0
-
delete
@NotNull public static Set<File> delete(@NotNull File fileOrDirectory, @NotNull FileFilter fileFilter, int numAttempts, @Nullable FileUtil.FilesDeleteListener deleteListener)
Removes files infileOrDirectory
, skipping all files that do not matchfileFilter
as well as all their subtitles/subfolders iffileFilter
is a directory. Be aware using the method in cases when directory may contain lot of files (>100k). Because of implementation this method requires O(n) memory because it collects visited and removed files. It may cause OOME (especially on agent side) just because a lot of File instances and not so much available memory on agent see TW-67058
-
delete
public static boolean delete(@NotNull File file)
Removes specified file or directory, same as FileUtil.delete(file, 10).- Parameters:
file
- file or directory to remove- Returns:
- true if file or directory was removed and false otherwise
-
deleteDirNative
public static boolean deleteDirNative(@NotNull File dir) throws ExecutionException
Deletes dir using native command rd for windows and rm for *nix- Parameters:
dir
- - dir to delete- Returns:
- true, if delete process returned 0 and target dir doesn't exist anymore, false otherwise
- Throws:
ExecutionException
-
deleteFiles
public static Collection<File> deleteFiles(@NotNull Collection<File> filesToDelete)
Deletes the given files, in several attempts, if needed.- Parameters:
filesToDelete
- files to delete - files only, not directories. The files that don't exist are silently ignored.- Returns:
- if all files were successfully deleted - an empty collection; or the files we could not to delete.
- Since:
- 8.1
-
isEmptyDir
public static boolean isEmptyDir(@NotNull File dir)
Returns true if directory is empty or does not exist and false otherwise.- Parameters:
dir
- directory- Returns:
- true if dir is empty or does not exist
-
isReadonly
public static boolean isReadonly(@NotNull File file)
Returns true if file is readonly and false otherwise- Parameters:
file
- file- Returns:
- true if file is readonly
-
fixDirectoryName
@NotNull public static String fixDirectoryName(@NotNull String name)
Fixes directory name: replaces all dangerous characters with '_'.- Parameters:
name
- name of the directory to fix- Returns:
- name with all 'dangerous' characters replaced with '_'
-
fixDirectoryNameAllowUnicode
@NotNull public static String fixDirectoryNameAllowUnicode(String name)
Fixes directory name in relaxed manner. Replaces dangerous punctuation with '_'. Allows symbols of unicode "Letter" category.- Parameters:
name
- name of the directory to fix- Returns:
- fixed name.
-
isBadDirectoryName
public static boolean isBadDirectoryName(@NotNull String name)
Checks whether specified name contains dangerous characters which might prevent successful directory creation.- Parameters:
name
- name to check (just name not path)- Returns:
- true if directory with given name cannot be created because of invalid characters in it
-
normalizeSeparator
@NotNull public static String normalizeSeparator(@NotNull String filePath)
Replace all separators like / and \ to File.separatorChar- Parameters:
filePath
- path to ve normalized- Returns:
- path with replaced separators
-
normalizeRelativePath
@NotNull public static String normalizeRelativePath(@NotNull String path)
Normalizes relative path by eliminating all possible path/../ /./ ./path combinations Doesn't check if the provided path is relative, but may return unexpected result for absolute paths.- Parameters:
path
- relative path- Returns:
- normalized paths with all slashes replaced with '/' and all dot combinations removed (if possible)
- Since:
- 4.0.2
-
normalizeAbsolutePath
@NotNull public static String normalizeAbsolutePath(@NotNull String path)
Normalizes absolute path by eliminating all possible path/../ /./ ./path combinations. Throws IllegalArgumentException if the specified path is not absolute (in terms of java.io.File#isAbsolute()).- Parameters:
path
- absolute path- Returns:
- normalized paths with all slashes replaced with File.separatorChar and all dot combinations removed (if possible)
- Throws:
IllegalArgumentException
- if the specified path is not absolute.- Since:
- 9.0
-
sortFiles
public static void sortFiles(@NotNull File[] files)
-
getCommonParentFile
@Nullable public static File getCommonParentFile(@NotNull File file1, @NotNull File file2)
-
getCommonParent
@NotNull @Deprecated public static String getCommonParent(@NotNull String firstUrl, @NotNull String secondUrl)
Deprecated.
-
isFileSeparator
public static boolean isFileSeparator(char c1)
-
getCanonicalFile
@NotNull public static File getCanonicalFile(@NotNull File file)
Attempts to obtain canonical file from the specified file and if it fails returns absolute file.- Parameters:
file
- file- Returns:
- see above
-
checkTmpDir
public static void checkTmpDir()
Checks if it is allowed to use tmpDir taken from "java.io.tmpdir" system property- Throws:
IllegalStateException
- if there is no access to temp dir.
-
findFile
@Nullable public static File findFile(@NotNull FileFilter filter, @NotNull File... directories)
Searches for a file in the specified directories recursively.- Parameters:
filter
- filter which checks whether file is acceptabledirectories
- directories to search for (recursively)- Returns:
- first found file or null
-
findFiles
@NotNull public static Collection<File> findFiles(@NotNull FileFilter filter, @NotNull File... directories)
Searches for files in the specified directories recursively.- Parameters:
filter
- filter which checks whether file is acceptabledirectories
- directories to search for (recursively)- Returns:
- all found files
-
listFilesRecursively
public static <C extends Collection<String>> C listFilesRecursively(@NotNull File dir, @NotNull String prefix, boolean includeDirs, int depthLimit, @Nullable Predicate<File> predicate, @NotNull C collection)
Traverses the given directory and retrieves all files (and nested directories, if specified). Puts the found files and directories into the given collection as strings, where each string is a relative path from the given directory, with '/' path separator (independent on the current OS).If the includeDirs option is false, only files are listed. Empty directories are skipped. If this option is true, all directories are included (empty and non-empty) as separated entries.
- Type Parameters:
C
- type of the destination collection.- Parameters:
dir
- directory to travers.prefix
- prefix that will be able to each entry.includeDirs
- include directories as separated entries.depthLimit
- recursion depth; 0 means non-recursive;Integer.MAX_VALUE
means infinite depth.predicate
- a predicate that is applied to each file or directory; if not met - file or directory will not be included and the directory will not be traversed in.collection
- destination collection where to put found file entries (must be writable).- Returns:
- the given destination collection.
- Since:
- 7.1
-
listFiles
@NotNull public static File[] listFiles(@NotNull File directory, @NotNull FilenameFilter filter)
A simple wrapper aroundfile.listFiles(filter)
that handles possiblenull
result. In this case an empty array is returned.- Parameters:
directory
- the filefilter
- the filter to apply- Returns:
- the array of inner file names (possibly empty)
-
listFiles
@NotNull public static File[] listFiles(@NotNull File directory)
A simple wrapper aroundfile.listFiles(filter)
that handles possiblenull
result. In this case an empty array is returned.- Parameters:
directory
- the file- Returns:
- the array of inner file names (possibly empty)
- Since:
- 2022.1
-
getFreeSpace
@Nullable public static Long getFreeSpace(@NotNull File file)
Computes free space on the disk that contains a file- Parameters:
file
- file to select disk- Returns:
- free space in bytes or null is operation is not supported by current JVM
- Since:
- 5.0
-
getFreeSpaceKB
@Deprecated @NotNull public static Long getFreeSpaceKB(@NotNull File dir) throws IOException
Deprecated.since 10.0. UsegetFreeSpaceBytesSafe(File)
insteadGets free space in kilobytes- Parameters:
dir
- path to get free space for- Returns:
- free space in kilobytes
- Throws:
IOException
- if an error occurs when finding the free space
-
freeSpaceKb
public static long freeSpaceKb(@NotNull String path) throws IOException
- Throws:
IOException
-
getFreeSpaceBytesSafe
@NotNull public static Long getFreeSpaceBytesSafe(@NotNull File dir) throws IOException
Gets free space in bytes avoidingLong
overflow if free space exceeds 2^63 bytes- Parameters:
dir
- path to get free space for- Returns:
- actual free space in bytes, if space does not exceed 2^63,
Long.MAX_VALUE
otherwise - Throws:
IOException
- if an error occurs when finding the free space
-
copy
public static void copy(@NotNull File from, @NotNull File to) throws IOException
- Throws:
IOException
-
copy
public static void copy(@NotNull InputStream from, @NotNull File to) throws IOException
- Throws:
IOException
-
areTheSame
public static boolean areTheSame(@Nullable File file1, @Nullable File file2) throws IOException
Checks that both file pointers specify the same object. So, in Linux it should denote symbolic links. In Windows it should take into account that names are case insensitive.Note: it also returns true if both pointers are null.
- Parameters:
file1
- the first file pointer.file2
- the second file pointer.- Returns:
- sameness.
- Throws:
IOException
-
convertAntToRegexp
@NotNull public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash)
- Parameters:
antPattern
- ant-style path pattern- Returns:
- java regexp pattern. Note that no matter whether forward or backward slashes were used in the antPattern the returned regexp pattern will use forward slashes ('/') as file separators. Paths containing windows-style backslashes must be converted before matching against the resulting regexp
- See Also:
FileUtil.toSystemIndependentName(java.lang.String)
-
getExtension
@NotNull public static String getExtension(@NotNull String fileNameWithDirectory)
Unlike com.intellij.openapi.util.io.FileUtil.getExtension, can use this with full file name (including directory name).- Parameters:
fileNameWithDirectory
- full file name including directory- Returns:
- file extension
-
getNameWithoutExtension
@NotNull public static String getNameWithoutExtension(@NotNull String name)
-
getName
@NotNull public static String getName(@NotNull String path)
Gets name of the file in platform-independent way (unlike new File(path).getName()) For directories, gets name of the directory- Since:
- 2018.1.2
-
setExectuableAttribute
public static void setExectuableAttribute(@NotNull String path, boolean executableFlag) throws IOException
Set executable attribute, it makes sense only on non-windows platforms.- Parameters:
path
- the path to useexecutableFlag
- new value of executable attribute- Throws:
IOException
- if there is a problem with setting the flag
-
checkContentEqual
public static boolean checkContentEqual(@NotNull File file1, @NotNull File file2)
Check both files exist and are same byte-by-byte.- Parameters:
file1
- first filefile2
- second file- Returns:
- true if both files exist and have exactly same content
-
haveEqualContentIgnoringLineEndings
public static boolean haveEqualContentIgnoringLineEndings(@NotNull File file1, @NotNull File file2) throws IOException
Check both files exist and have same content ignoring line-endings and leading/trailing spaces.- Parameters:
file1
- first filefile2
- second file- Returns:
- true if both files exist and have same content
- Throws:
IOException
-
isAncestor
public static boolean isAncestor(@NotNull File ancestor, @NotNull File file, boolean strict)
Check if theancestor
is an ancestor offile
. Overrides the same method fromFileUtil
. Please do not use the method from super class directly - it can cause the compilation problems.- Parameters:
ancestor
- the filefile
- the filestrict
- iffalse
then this method returnstrue
ifancestor
andfile
are equal- Returns:
true
ifancestor
is parent offile
;false
otherwise
-
copy
public static void copy(@NotNull InputStream is, @NotNull OutputStream os) throws IOException
Same as copyStream.- Throws:
IOException
-
isBinaryFile
public static boolean isBinaryFile(@NotNull File file) throws IOException
Returns whether a specifiedfile
is a binary file.- Parameters:
file
- the file to analyse- Returns:
- true iff
file
is binary - Throws:
IOException
- in case of I/O errors
-
isBinaryData
public static boolean isBinaryData(@NotNull byte[] data, int size)
Returns whether specified byte array represents binary data (not text)- Parameters:
data
- the byte arraysize
- size to check- Returns:
- true iff
data
array represents binary data
-
isTextData
public static boolean isTextData(@NotNull byte[] data, int size)
Returns whether specified byte array represents text data (not binary)- Parameters:
data
- the byte arraysize
- size to check- Returns:
- true iff
data
array represents text data
-
isSymlink
public static boolean isSymlink(@NotNull File file)
Checks whetherfile
is a symlink by resolving absolute path into real (canonical) oneNote that if NIO.2 API is unavailable (Java 1.6 and earlier), symbolic links can't be reliably detected in the following cases:
- broken links in UNIX (
link -> nonexistent
, indirectly detectable via checking thatFile.isFile()
andFile.isDirectory()
) both returnfalse
; - (broken) links referencing themselves in UNIX (
link -> link
); - (broken) cyclic links in UNIX (
link0 -> link1
,link1 -> link0
); - NTFS links.
Hard links (to files, Windows(NTFS)/Linux/Solaris) and directory junctions (NTFS) are not detectable even using NIO.2 API.
- Parameters:
file
- to check- Returns:
- true if the
file
is a symlink, false otherwise - Since:
- 8.1
- broken links in UNIX (
-
createSymlink
public static boolean createSymlink(@NotNull File target, @NotNull File symlinkFile)
Attempts to create a symlink atsymlinkFile
that points totarget
- Parameters:
target
- - file or directory that symlink will point tosymlinkFile
- - a symlink location- Returns:
- true if symlink was created and points to the desired file/directory.
false otherwise - Since:
- 8.1
-
getNameOrAbsolutePath
public static String getNameOrAbsolutePath(@NotNull File baseDir, @NotNull File checkDir)
Checks whether directory lies directly under baseDir. Returns its name when true and absolute path otherwise.- Parameters:
checkDir
- - dir to checkbaseDir
- - base dir to check against- Returns:
- checkDir name, if it lies directly under baseDir and absolute path of checkDir otherwise.
- Since:
- 8.1
-
getUTF8Reader
public static Reader getUTF8Reader(@NotNull File file) throws FileNotFoundException
Returns Reader with utf-8 encoding to read the file, because FileReader uses default platform encoding- Parameters:
file
- file to read- Returns:
- Reader to use
- Throws:
FileNotFoundException
- if FileNotFoundException exception occurs
-
-