public class FileSystemUtils extends java.lang.Object
Modifier and Type | Field and Description |
---|---|
static java.lang.String |
METRIC_SYSTEM_UNITS
String containing the unit letters for units in the metric system (K for
kilo, M for mega, ...).
|
static java.lang.String |
TEMP_DIR_PATH
The path to the directory used by Java to store temporary files
|
static char |
UNIX_SEPARATOR
Unix file path separator
|
static java.lang.String |
UTF8_ENCODING
Encoding for UTF-8.
|
static char |
WINDOWS_SEPARATOR
Windows file path separator
|
Constructor and Description |
---|
FileSystemUtils() |
Modifier and Type | Method and Description |
---|---|
static java.io.InputStream |
autoDecompressStream(java.io.InputStream in)
Transparently creates a stream for decompression if the provided stream is
compressed.
|
static void |
close(java.io.Closeable closeable)
Convenience method for calling
close(Closeable, ILogger) with a
null -logger. |
static void |
close(java.io.Closeable closeable,
ILogger logger)
This method can be used to simplify the typical
finally -block
of code dealing with streams and readers/writers. |
static void |
close(ZipFile zipFile)
Closes the given ZIP file quietly, i.e.
|
static java.io.File |
commonRoot(java.lang.Iterable<? extends java.io.File> files)
Determines the root directory from a collection of files.
|
static java.lang.String |
concatenatePaths(java.lang.String firstParent,
java.lang.String... paths)
Concatenates all path parts into a single path with normalized separators.
|
static boolean |
contentsEqual(java.io.File file1,
java.io.File file2)
Checks whether two files have the same content.
|
static int |
copy(java.io.InputStream input,
java.io.OutputStream output)
Copy an input stream to an output stream.
|
static void |
copyFile(java.io.File sourceFile,
java.io.File targetFile)
Copy a file.
|
static void |
copyFile(java.lang.String sourceFilename,
java.lang.String targetFilename)
Copy a file.
|
static int |
copyFiles(java.io.File sourceDirectory,
java.io.File targetDirectory,
java.io.FileFilter fileFilter)
Copy all files specified by a file filter from one directory to another.
|
static int |
createJARFile(java.io.File jarFile,
java.io.File sourceDirectory,
java.io.FileFilter filter)
Create jar file from all files in a directory.
|
static java.lang.String |
createRelativePath(java.io.File path,
java.io.File relativeTo)
Returns a string describing the relative path to the given directory.
|
static void |
deleteFile(java.io.File file)
Deletes the given file and throws an exception if this fails.
|
static void |
deleteRecursively(java.io.File directory)
Recursively delete directories and files.
|
static void |
ensureDirectoryExists(java.io.File directory)
Checks if a directory exists.
|
static void |
ensureParentDirectoryExists(java.io.File file)
Checks if the parent directory of a file exists.
|
static java.io.File |
escapeReservedFileNames(java.io.File file)
Returns a new file with all file path segments that are reserved (windows)
path names escaped.
|
static java.io.File |
extractJarFileFromJarURL(java.net.URL url)
Returns the JAR file for an URL with protocol 'jar'.
|
static java.lang.String |
getFileExtension(java.io.File file)
Returns the extension of the file.
|
static java.lang.String |
getFileExtension(java.lang.String path)
Returns the extension of the file at the given path.
|
static java.lang.String |
getFilenameWithoutExtension(java.io.File file)
Returns the name of the given file without extension.
|
static java.lang.String |
getFilenameWithoutExtension(java.lang.String fileName)
Returns the name of the given file without extension.
|
static long |
getLastModifiedTimestamp(java.io.File file)
Determines the last modified timestamp in a platform agnostic way.
|
static java.lang.String |
getLastPathSegment(java.lang.String filePath)
Returns the last path segment (i.e.
|
static java.io.File |
getNonExistingFile(java.io.File file)
Returns a file that does not exist in the same directory of the given file.
|
static java.lang.String[] |
getPathSegments(java.lang.String filePath)
Returns the segments of a path.
|
static java.io.File |
getTmpDir()
Obtains the system's temporary directory
|
static java.io.File |
getUserHomeDir()
Obtains the current user's home directory
|
static java.io.File |
getWorkspaceDir()
Obtains the current working directory.
|
static boolean |
isAbsolutePath(java.lang.String filename)
Returns whether a filename represents an absolute path.
|
static boolean |
isReadableFile(java.io.File... files)
Returns whether the given file is non-null, a plain file and is readable.
|
static java.util.List<java.lang.String> |
listFilesInSameLocationForURL(java.net.URL baseUrl) |
static java.util.List<java.lang.String> |
listFilesInSameLocationForURL(java.net.URL baseUrl,
boolean includeSubfolders)
Lists the names of all simple files (i.e.
|
static java.util.List<java.io.File> |
listFilesRecursively(java.io.File directory)
Returns a list of all files and directories contained in the given directory
and all subdirectories.
|
static java.util.List<java.io.File> |
listFilesRecursively(java.io.File directory,
java.io.FileFilter filter)
Returns a list of all files and directories contained in the given directory
and all subdirectories matching the filter provided.
|
static java.util.List<java.lang.String> |
listTopLevelClassesInJarFile(java.io.File jarFile)
Extract all top-level classes in the given JAR and returns a list of their
fully qualified class names.
|
static void |
mergeTemplate(java.io.File templateFile,
java.io.File outFile,
java.lang.Object... arguments)
Loads template file with a
Format string, formats it and writes result to file.
|
static java.io.InputStream |
mergeTemplate(java.io.InputStream inStream,
java.lang.Object... arguments)
Loads template file with a
Format string, formats it and provides result as stream.
|
static void |
mkdir(java.io.File dir)
Creates a directory and throws an exception if this fails.
|
static void |
mkdirs(java.io.File dir)
Creates a directory and all required parent directories.
|
static java.io.File |
newFile(java.io.File parentFile,
java.lang.String... pathElements)
Constructs a file from a base file by appending several path elements.
|
static java.lang.String |
normalizeSeparators(java.lang.String path)
Replace platform dependent separator char with forward slashes to create
system-independent paths.
|
static java.io.InputStream |
openJarFileEntry(java.util.jar.JarFile jarFile,
java.lang.String entryName)
Opens an
InputStream for the entry with the given name in the given
JAR file |
static long |
parseDataSize(java.lang.String dataSize)
Converts the given human readable data size to the corresponding number of
bytes.
|
static java.lang.String |
readFile(java.io.File file)
Read file content into a string using the default encoding for the platform.
|
static java.lang.String |
readFile(java.io.File file,
java.nio.charset.Charset encoding)
Read file content into a string using the given encoding.
|
static byte[] |
readFileBinary(java.io.File file)
Read file content into a byte array.
|
static byte[] |
readFileBinary(java.lang.String filePath)
Read file content into a byte array.
|
static java.lang.String |
readFileSystemIndependent(java.io.File file)
Reads a file using UTF-8 encoding and normalizes line breaks (replacing
"\n\r" and "\r" with "\n").
|
static java.lang.String |
readFileUTF8(java.io.File file)
Read file content into a string using UTF-8 encoding.
|
static java.lang.String |
readFileUTF8WithLineBreakNormalization(java.io.File file)
Read file content into a string using UTF-8 encoding and normalize the line
breaks.
|
static java.util.List<java.lang.String> |
readLines(java.io.File file,
java.nio.charset.Charset encoding)
Read file content into a list of lines (strings) using the given encoding.
|
static java.util.List<java.lang.String> |
readLinesUTF8(java.io.File file)
Read file content into a list of lines (strings) using UTF-8 encoding.
|
static java.util.List<java.lang.String> |
readLinesUTF8(java.lang.String filePath)
Read file content into a list of lines (strings) using UTF-8 encoding.
|
static java.util.Properties |
readProperties(CollectionUtils.SupplierWithException<? extends java.io.InputStream,java.io.IOException> streamSupplier)
Reads properties from a properties stream.
|
static java.util.Properties |
readProperties(java.io.File propertiesFile)
Reads properties from a properties file.
|
static java.util.Properties |
readProperties(Resource resource)
Reads properties from a properties resource.
|
static java.lang.String |
readStream(java.io.InputStream input)
Read input stream into string.
|
static java.lang.String |
readStream(java.io.InputStream input,
java.nio.charset.Charset encoding)
Read input stream into string.
|
static byte[] |
readStreamBinary(java.io.InputStream input)
Read input stream into raw byte array.
|
static java.lang.String |
readStreamUTF8(java.io.InputStream input)
Read input stream into string.
|
static void |
recursivelyRemoveDirectoryIfEmpty(java.io.File path)
Removes the given path if it is an empty directory and recursively parent
directories if the only child was deleted.
|
static void |
renameFileTo(java.io.File file,
java.io.File dest)
Renames the given file and throws an exception if this fails.
|
static java.lang.String |
replaceFilePathFilenameWith(java.lang.String uniformPath,
java.lang.String newFileName)
Replaces the file name of the given path with the given new extension.
|
static void |
safeRead(java.io.InputStream in,
byte[] data)
Reads bytes of data from the input stream into an array of bytes until the
array is full.
|
static void |
safeRead(java.io.InputStream in,
byte[] data,
int offset,
int length)
Reads
length bytes of data from the input stream into an array
of bytes and stores it at position offset . |
static void |
sort(java.util.List<java.io.File> files)
Compares files based on the lexical order of their fully qualified names.
|
static java.io.Reader |
streamReader(java.io.InputStream in,
java.nio.charset.Charset encoding)
Returns a reader that wraps the given input stream.
|
static java.lang.String |
toSafeFilename(java.lang.String name)
Returns a safe filename that can be used for downloads.
|
static void |
unjar(java.io.File jarFile,
java.io.File targetDirectory)
Extract a JAR file to a directory.
|
static void |
unzip(java.io.File zipFile,
java.io.File targetDirectory)
Extract a ZIP file to a directory.
|
static java.util.List<java.lang.String> |
unzip(java.io.File zipFile,
java.io.File targetDirectory,
java.lang.String prefix,
java.nio.charset.Charset charset)
Extract the entries of ZIP file to a directory.
|
static java.util.List<java.lang.String> |
unzip(java.io.InputStream inputStream,
java.io.File targetDirectory)
Extract entries of a zip file input stream to a directory.
|
static java.util.List<java.lang.String> |
unzip(ZipFile zip,
java.io.File targetDirectory,
java.lang.String prefix)
Extract entries of a ZipFile to a directory when the ZipFile is created
externally.
|
static void |
writeFile(java.io.File file,
java.lang.String content)
Write string to a file with the default encoding.
|
static void |
writeFile(java.io.File file,
java.lang.String content,
java.lang.String encoding)
Write string to a file.
|
static void |
writeFileBinary(java.io.File file,
byte[] bytes)
Writes the given bytes to the given file.
|
static void |
writeFileUTF8(java.io.File file,
java.lang.String content)
Write string to a file with UTF8 encoding.
|
static void |
writeFileWithBOM(java.io.File file,
java.lang.String content,
EByteOrderMark bom)
Write string to a file using a UTF encoding.
|
static void |
writeLines(java.io.File file,
java.util.Collection<java.lang.String> lines)
Writes the given collection of String as lines into the specified file.
|
public static final java.lang.String UTF8_ENCODING
public static final java.lang.String TEMP_DIR_PATH
public static final char UNIX_SEPARATOR
public static final char WINDOWS_SEPARATOR
public static final java.lang.String METRIC_SYSTEM_UNITS
public FileSystemUtils()
public static int copy(java.io.InputStream input, java.io.OutputStream output) throws java.io.IOException
input
- input streamoutput
- output streamjava.io.IOException
- if an IO exception occurs.public static void copyFile(java.io.File sourceFile, java.io.File targetFile) throws java.io.IOException
java.io.IOException
public static void copyFile(java.lang.String sourceFilename, java.lang.String targetFilename) throws java.io.IOException
java.io.IOException
public static int copyFiles(java.io.File sourceDirectory, java.io.File targetDirectory, java.io.FileFilter fileFilter) throws java.io.IOException
fileFilter
- filter to specify file types. If all files should be copied, use
FileOnlyFilter
.java.io.IOException
public static int createJARFile(java.io.File jarFile, java.io.File sourceDirectory, java.io.FileFilter filter) throws java.io.IOException
filter
- filter to specify file types. If all files should be copied, use
FileOnlyFilter
.java.io.IOException
public static java.lang.String createRelativePath(java.io.File path, java.io.File relativeTo) throws java.io.IOException
path
- the path to convert to a relative path (must describe an existing
directory)relativeTo
- the anchor (must describe an existing directory)java.io.IOException
- if creation of canonical pathes fails.public static void deleteRecursively(java.io.File directory)
public static void deleteFile(java.io.File file) throws java.io.IOException
java.io.IOException
File.delete()
public static void renameFileTo(java.io.File file, java.io.File dest) throws java.io.IOException
java.io.IOException
File.renameTo(File)
public static void mkdir(java.io.File dir) throws java.io.IOException
java.io.IOException
File.mkdir()
public static void mkdirs(java.io.File dir) throws java.io.IOException
java.io.IOException
File.mkdirs()
public static void ensureDirectoryExists(java.io.File directory) throws java.io.IOException
java.io.IOException
- if directories couldn't be created.public static void ensureParentDirectoryExists(java.io.File file) throws java.io.IOException
java.io.IOException
- if directories couldn't be created.public static java.util.List<java.io.File> listFilesRecursively(java.io.File directory)
This method knows nothing about (symbolic and hard) links, so care should be taken when traversing directories containing recursive links.
directory
- the directory to start the search from.public static java.util.List<java.io.File> listFilesRecursively(java.io.File directory, java.io.FileFilter filter)
The file filter may or may not exclude directories.
This method knows nothing about (symbolic and hard) links, so care should be taken when traversing directories containing recursive links.
directory
- the directory to start the search from. If this is null or the
directory does not exist, an empty list is returned.filter
- the filter used to determine whether the result should be
included. If the filter is null, all files and directories are
included.public static java.util.List<java.lang.String> listFilesInSameLocationForURL(java.net.URL baseUrl) throws java.io.IOException
java.io.IOException
listFilesInSameLocationForURL(URL, boolean)
public static java.util.List<java.lang.String> listFilesInSameLocationForURL(java.net.URL baseUrl, boolean includeSubfolders) throws java.io.IOException
java.io.IOException
public static java.util.List<java.lang.String> listTopLevelClassesInJarFile(java.io.File jarFile) throws java.io.IOException
java.io.IOException
public static java.lang.String getFileExtension(java.io.File file)
null
, if the file has no extension (i.e. if a filename
contains no '.'), returns the empty string if the '.' is the
filename's last character.public static java.lang.String getFileExtension(java.lang.String path)
public static java.lang.String getFilenameWithoutExtension(java.io.File file)
public static java.lang.String getFilenameWithoutExtension(java.lang.String fileName)
public static java.lang.String getLastPathSegment(java.lang.String filePath)
public static java.lang.String[] getPathSegments(java.lang.String filePath)
public static java.io.File newFile(java.io.File parentFile, java.lang.String... pathElements)
File.File(File, String)
but allows to define
multiple child levels.pathElements
- list of elements. If this is empty, the parent is returned.public static java.lang.String readFile(java.io.File file) throws java.io.IOException
java.io.IOException
EByteOrderMark
public static java.lang.String readFileUTF8(java.io.File file) throws java.io.IOException
java.io.IOException
EByteOrderMark
public static java.lang.String readFileUTF8WithLineBreakNormalization(java.io.File file) throws java.io.IOException
java.io.IOException
EByteOrderMark
,
StringUtils.normalizeLineSeparatorsPlatformSpecific(String)
public static java.lang.String readFile(java.io.File file, java.nio.charset.Charset encoding) throws java.io.IOException
java.io.IOException
EByteOrderMark
public static java.util.List<java.lang.String> readLines(java.io.File file, java.nio.charset.Charset encoding) throws java.io.IOException
readFile(File)
.java.io.IOException
public static java.util.List<java.lang.String> readLinesUTF8(java.lang.String filePath) throws java.io.IOException
readFile(File)
.java.io.IOException
public static java.util.List<java.lang.String> readLinesUTF8(java.io.File file) throws java.io.IOException
readFile(File)
.java.io.IOException
public static byte[] readFileBinary(java.lang.String filePath) throws java.io.IOException
java.io.IOException
public static byte[] readFileBinary(java.io.File file) throws java.io.IOException
java.io.IOException
public static void unjar(java.io.File jarFile, java.io.File targetDirectory) throws java.io.IOException
java.io.IOException
public static void unzip(java.io.File zipFile, java.io.File targetDirectory) throws java.io.IOException
java.io.IOException
public static java.util.List<java.lang.String> unzip(java.io.File zipFile, java.io.File targetDirectory, java.lang.String prefix, java.nio.charset.Charset charset) throws java.io.IOException
prefix
- Sets a prefix for the the entry names (paths) which should be
extracted. Only entries which starts with the given prefix are
extracted. If prefix is null
or empty all entries are
extracted. The prefix will be stripped form the extracted entries.charset
- defines the Charset
of the ZIP file. If null
,
the standard of ZipFile
is used (which is UTF-8).java.io.IOException
public static java.util.List<java.lang.String> unzip(ZipFile zip, java.io.File targetDirectory, java.lang.String prefix) throws java.io.IOException
java.io.IOException
public static java.util.List<java.lang.String> unzip(java.io.InputStream inputStream, java.io.File targetDirectory) throws java.io.IOException
java.io.IOException
public static void writeFile(java.io.File file, java.lang.String content) throws java.io.IOException
java.io.IOException
public static void writeLines(java.io.File file, java.util.Collection<java.lang.String> lines) throws java.io.IOException
java.io.IOException
public static void writeFileUTF8(java.io.File file, java.lang.String content) throws java.io.IOException
java.io.IOException
public static void writeFile(java.io.File file, java.lang.String content, java.lang.String encoding) throws java.io.IOException
java.io.IOException
public static void writeFileWithBOM(java.io.File file, java.lang.String content, EByteOrderMark bom) throws java.io.IOException
java.io.IOException
public static void writeFileBinary(java.io.File file, byte[] bytes) throws java.io.IOException
java.io.IOException
public static void mergeTemplate(java.io.File templateFile, java.io.File outFile, java.lang.Object... arguments) throws java.io.IOException
templateFile
- the template file with the format stringoutFile
- the target file, parent directories are created automatically.arguments
- the formatting arguments.java.io.IOException
- if an IO exception occurs or the template file defines an illegal
format.public static java.io.InputStream mergeTemplate(java.io.InputStream inStream, java.lang.Object... arguments) throws java.io.IOException
inStream
- stream that provides the template format stringarguments
- the formatting arguments.java.io.IOException
- if an IOException occurs or the template file defines an illegal
format.public static java.lang.String readStream(java.io.InputStream input) throws java.io.IOException
java.io.IOException
public static java.lang.String readStreamUTF8(java.io.InputStream input) throws java.io.IOException
java.io.IOException
public static java.lang.String readStream(java.io.InputStream input, java.nio.charset.Charset encoding) throws java.io.IOException
java.io.IOException
public static byte[] readStreamBinary(java.io.InputStream input) throws java.io.IOException
java.io.IOException
public static java.io.Reader streamReader(java.io.InputStream in, java.nio.charset.Charset encoding) throws java.io.IOException
java.io.IOException
public static java.util.Properties readProperties(java.io.File propertiesFile) throws java.io.IOException
java.io.IOException
public static java.util.Properties readProperties(Resource resource) throws java.io.IOException
java.io.IOException
public static java.util.Properties readProperties(CollectionUtils.SupplierWithException<? extends java.io.InputStream,java.io.IOException> streamSupplier) throws java.io.IOException
java.io.IOException
public static java.io.File commonRoot(java.lang.Iterable<? extends java.io.File> files) throws java.io.IOException
This method does not require the input files to exist.
files
- Collection of files for which root directory gets determined. This
collection is required to contain at least 2 files. If it does
not, an AssertionError is thrown.java.lang.AssertionError
- If less than two different files are provided whereas fully
qualified canonical names are used for comparison.java.io.IOException
- Since canonical paths are used for determination of the common
root, and File.getCanonicalPath()
can throw
IOException
s.public static java.io.InputStream autoDecompressStream(java.io.InputStream in) throws java.io.IOException
GZIPInputStream
java.io.IOException
public static void close(ZipFile zipFile)
null
safe.public static void close(java.io.Closeable closeable)
close(Closeable, ILogger)
with a
null
-logger.public static void close(java.io.Closeable closeable, ILogger logger)
finally
-block
of code dealing with streams and readers/writers. It checks if the provided
closeable is null
. If not it closes it. An exception thrown
during the close operation is logged with the provided logger with level
warn. If the provided logger is null
, no logging is
performed. If no logging is required, method close(Closeable)
may
also be used.public static void sort(java.util.List<java.io.File> files)
public static java.lang.String normalizeSeparators(java.lang.String path)
public static java.io.File extractJarFileFromJarURL(java.net.URL url)
public static boolean isAbsolutePath(java.lang.String filename)
File.isAbsolute()
is
operating system specific.public static void safeRead(java.io.InputStream in, byte[] data) throws java.io.IOException, java.io.EOFException
InputStream.read(byte[])
may read
less than the requested number of bytes, while this method ensures the data
is complete.in
- the stream to read from.data
- the stream to read from.java.io.IOException
- if reading the underlying stream causes an exception.java.io.EOFException
- if the end of file was reached before the requested data was
read.public static void safeRead(java.io.InputStream in, byte[] data, int offset, int length) throws java.io.IOException, java.io.EOFException
length
bytes of data from the input stream into an array
of bytes and stores it at position offset
. This method blocks
until input data is available, end of file is detected, or an exception is
thrown.
The reason for this method is that InputStream.read(byte[], int, int)
may read less than the requested number of bytes, while this method ensures
the data is complete.in
- the stream to read from.data
- the stream to read from.offset
- the offset in the array where the first read byte is stored.length
- the length of data read.java.io.IOException
- if reading the underlying stream causes an exception.java.io.EOFException
- if the end of file was reached before the requested data was
read.public static java.io.File getTmpDir()
public static java.io.File getUserHomeDir()
public static java.io.File getWorkspaceDir()
public static boolean contentsEqual(java.io.File file1, java.io.File file2) throws java.io.IOException
java.io.IOException
public static java.io.InputStream openJarFileEntry(java.util.jar.JarFile jarFile, java.lang.String entryName) throws java.io.IOException
InputStream
for the entry with the given name in the given
JAR filejava.io.IOException
public static boolean isReadableFile(java.io.File... files)
public static java.lang.String concatenatePaths(java.lang.String firstParent, java.lang.String... paths)
public static void recursivelyRemoveDirectoryIfEmpty(java.io.File path) throws java.io.IOException
java.io.IOException
- if an I/O error during deletion occurs.public static java.io.File getNonExistingFile(java.io.File file)
public static long parseDataSize(java.lang.String dataSize)
public static long getLastModifiedTimestamp(java.io.File file) throws java.io.IOException
java.io.IOException
public static java.lang.String toSafeFilename(java.lang.String name)
public static java.io.File escapeReservedFileNames(java.io.File file)
public static java.lang.String readFileSystemIndependent(java.io.File file) throws java.io.IOException
java.io.IOException
public static java.lang.String replaceFilePathFilenameWith(java.lang.String uniformPath, java.lang.String newFileName)
replaceFilePathFilenameWith("xx", "yy")
returns
"yy"
replaceFilePathFilenameWith("xx/zz", "yy")
returns *
"xx/yy"
replaceFilePathFilenameWith("xx/zz/", "yy")
returns *
"xx/zz/yy"
replaceFilePathFilenameWith("", "yy")
returns *
"yy"