Modifier and Type | Field and Description |
---|---|
static String |
CHARSET_NAME_UTF_8
UTF-8 caracter set name.
|
static Charset |
CHARSET_UTF_8
UTF-8 caracter set.
|
static String |
COLLISION_FILE_NAME_INFIX |
static long |
GIGABYTE
1 GB in bytes.
|
Modifier and Type | Method and Description |
---|---|
static String |
addFinalSlash(String directory)
Add a trailing file separator character to the
given directory name if it does not already
end with one.
|
static boolean |
compareFiles(File f1,
File f2)
Compare the contents of two given files.
|
static boolean |
compareInputStreams(InputStream in1,
InputStream in2,
long length)
Compares two InputStreams.
|
static boolean |
compareInputStreams(InputStream in1,
InputStream in2,
long compareLength,
long minimumReadLength)
Compares two InputStreams.
|
static void |
copyDirectory(File sourceDirectory,
File destinationDirectory)
Copy a directory recursively.
|
static void |
copyDirectory(File sourceDirectory,
File destinationDirectory,
FileFilter fileFilter) |
static void |
copyFile(File sourceFile,
File destinationFile)
Copy a file.
|
static void |
copyFile(File sourceFile,
File destinationFile,
ProgressMonitor monitor) |
static void |
copyResource(Class<?> sourceResClass,
String sourceResName,
File destinationFile)
Copy a resource loaded by the class loader of a given class to a file.
|
static void |
copyResource(Class<?> sourceResClass,
String sourceResName,
String destinationFilename)
Copy a resource loaded by the class loader of a given class to a file.
|
static File |
createCollisionFile(File file) |
static File |
createUniqueIncrementalFolder(File rootFolder,
String prefix)
Tries to find a unique, not existing folder name under the given root folder
suffixed with a number.
|
static File |
createUniqueRandomFolder(File rootFolder,
String prefix)
Tries to find a unique, not existing folder name under the given root folder with a random
number (in hex format) added to the given prefix.
|
static File |
createUniqueRandomFolder(File rootFolder,
String prefix,
long maxIterations,
long uniqueOutOf)
Tries to find a unique, not existing folder name under the given root folder with a random
number (in hex format) added to the given prefix.
|
static File |
createUserTempDir(String prefix,
String suffix)
Get a user-dependent temp directory in every operating system and create it, if it does not exist.
|
static boolean |
deleteDirectoryRecursively(File dir)
This method deletes the given directory recursively.
|
static boolean |
deleteDirectoryRecursively(String dir)
This method deletes the given directory recursively.
|
static byte[] |
getBytesFromFile(File file) |
static File |
getFile(File file,
String... subDirs)
Get a file object from a base directory and a list of subdirectories or files.
|
static String |
getFileExtension(String fileName)
Get the extension of a filename.
|
static String |
getFileNameWithoutExtension(String fileName)
Get a filename without extension.
|
static long |
getLastModifiedNoFollow(File file) |
static long |
getLastModifiedNoFollow(java.nio.file.Path path) |
static String |
getRelativePath(File baseDir,
File file)
This method finds - if possible - a relative path for addressing
the given
file from the given baseDir . |
static String |
getRelativePath(File baseDir,
String file)
This method finds - if possible - a relative path for addressing
the given
file from the given baseDir . |
static String |
getRelativePath(String baseDir,
String file)
This method finds - if possible - a relative path for addressing
the given
file from the given baseDir . |
static File |
getTempDir()
Get the temporary directory.
|
static File |
getUserHome() |
static File |
getUserTempDir(String prefix,
String suffix)
Get a user-dependent temp directory in every operating system.
|
static String |
readTextFile(File f)
Read a UTF-8 encoded text file and return the contents as string.
|
static String |
readTextFile(File f,
String encoding)
Read a text file and return the contents as string.
|
static String |
readTextFile(InputStream in)
Read a text file from an
InputStream using
UTF-8 encoding. |
static String |
readTextFile(InputStream in,
String encoding)
Read a text file from an
InputStream using
the given encoding. |
static void |
replaceTemplateVariables(File destinationFile,
File templateFile,
String characterSet,
Map<?,?> variables)
Generate a file from a template.
|
static String |
replaceTemplateVariables(String template,
Map<?,?> variables)
Replace variables (formatted
"${variable}" ) with their values
passed in the map variables . |
static void |
replaceTemplateVariables(Writer writer,
Reader reader,
Map<?,?> variables)
Copy contents from the given reader to the given writer while
replacing variables which are formatted
"${variable}" with their values
passed in the map variables . |
static void |
setLastModifiedNoFollow(File file,
long lastModified) |
static void |
setLastModifiedNoFollow(java.nio.file.Path path,
long lastModified) |
static String |
simplifyPath(File path)
This method removes double slashes, single-dot-directories and double-dot-directories
from a path.
|
static String |
toPathString(java.nio.file.Path path) |
static long |
transferStreamData(InputStream in,
OutputStream out)
Transfer all available data from an
InputStream to an OutputStream . |
static long |
transferStreamData(InputStream in,
OutputStream out,
long inputOffset,
long inputLen)
Transfer data between streams.
|
static long |
transferStreamData(InputStream in,
OutputStream out,
long inputOffset,
long inputLen,
ProgressMonitor monitor) |
static void |
writeTextFile(File file,
String text)
Write text to a file using UTF-8 encoding.
|
static void |
writeTextFile(File file,
String text,
String encoding)
Write text to a file.
|
public static final String CHARSET_NAME_UTF_8
public static final Charset CHARSET_UTF_8
public static final long GIGABYTE
public static final String COLLISION_FILE_NAME_INFIX
public static String getRelativePath(File baseDir, String file) throws IOException
file
from the given baseDir
.
If it is not possible to denote file
relative to baseDir
,
the absolute path of file
will be returned.
Examples:
baseDir="/home/marco"
file="temp/jfire/jboss/bin/run.sh"
file="/home/marco/temp/jfire/jboss/bin/run.sh"
result="temp/jfire/jboss/bin/run.sh"
baseDir="/home/marco/workspace.jfire/JFireBase"
file="/home/marco/temp/jfire/jboss/bin/run.sh"
file="../../temp/jfire/jboss/bin/run.sh"
result="../../temp/jfire/jboss/bin/run.sh"
baseDir="/tmp/workspace.jfire/JFireBase"
file="/home/marco/temp/jfire/jboss/bin/run.sh"
result="/home/marco/temp/jfire/jboss/bin/run.sh"
(absolute, because relative is not possible)
baseDir
- This directory is used as start for the relative path. It can be seen as the working directory
from which to point to file
.file
- The file to point to.file
relative to baseDir
or the absolute path,
if a relative path cannot be formulated (i.e. they have no directory in common).IOException
- In case of an errorpublic static String getRelativePath(File baseDir, File file) throws IOException
file
from the given baseDir
.
If it is not possible to denote file
relative to baseDir
,
the absolute path of file
will be returned.
getRelativePath
for examples.baseDir
- This directory is used as start for the relative path. It can be seen as the working directory
from which to point to file
.file
- The file to point to.file
relative to baseDir
or the absolute path,
if a relative path cannot be formulated (i.e. they have no directory in common).IOException
- In case of an errorpublic static String getRelativePath(String baseDir, String file) throws IOException
file
from the given baseDir
.
If it is not possible to denote file
relative to baseDir
,
the absolute path of file
will be returned.
getRelativePath
for examples.baseDir
- This directory is used as start for the relative path. It can be seen as the working directory
from which to point to file
.file
- The file to point to.file
relative to baseDir
or the absolute path,
if a relative path cannot be formulated (i.e. they have no directory in common).IOException
- In case of an errorpublic static String simplifyPath(File path)
File.getCanonicalPath
, but
it does not resolve symlinks. This is essential for the method getRelativePath
,
because this method first tries it with a simplified path before using the canonical path
(prevents problems with iteration through directories, where there are symlinks).
Please note that this method makes the given path absolute!
path
- A path to simplify, e.g. "/../opt/java/jboss/../jboss/./bin/././../server/default/lib/."public static long transferStreamData(InputStream in, OutputStream out, long inputOffset, long inputLen) throws IOException
in
- The input streamout
- The output streaminputOffset
- How many bytes to skip before transferringinputLen
- How many bytes to transfer. -1 = allIOException
- if an error occurs.public static long transferStreamData(InputStream in, OutputStream out, long inputOffset, long inputLen, ProgressMonitor monitor) throws IOException
IOException
public static long transferStreamData(InputStream in, OutputStream out) throws IOException
InputStream
to an OutputStream
.
This is a convenience method for transferStreamData(in, out, 0, -1)
in
- The stream to read fromout
- The stream to write toIOException
- In case of an errorpublic static boolean deleteDirectoryRecursively(File dir)
Before diving into a subdirectory, it first tries to delete dir
. If this
succeeds, it does not try to dive into it. This way, this implementation is symlink-safe.
Hence, if dir
denotes a symlink to another directory, this method does
normally not delete the real contents of the directory.
Warning! It sometimes still deletes the contents! This happens, if the user has no permissions onto a symlinked directory (thus, the deletion before dive-in fails), but its contents. In this case, the method will dive into the directory (because the deletion failed and it therefore assumes it to be a real directory) and delete the contents.
We might later extend this method to do further checks (maybe call an OS program like we do in
#createSymlink(File, File, boolean)
).
dir
- The directory or file to deletetrue
if the file or directory does not exist anymore.
This means it either was not existing already before or it has been
successfully deleted. false
if the directory could not be
deleted.public static boolean deleteDirectoryRecursively(String dir)
dir
- The directory or file to deletepublic static File createUniqueIncrementalFolder(File rootFolder, String prefix) throws IOException
IOException
will be thrown.
Note that the creation of the directory is not completely safe. This method is synchronized, but other processes could "steal" the unique filename.
rootFolder
- The rootFolder to find a unique subfolder forprefix
- A prefix for the folder that has to be found.IOException
- in case of an errorpublic static File createUniqueRandomFolder(File rootFolder, String prefix, long maxIterations, long uniqueOutOf) throws IOException
The method will try to find a name for maxIterations
number
of itarations and use random numbers from 0 to uniqueOutOf
.
Note that the creation of the directory is not completely safe. This method is synchronized, but other processes could "steal" the unique filename.
rootFolder
- The rootFolder to find a unique subfolder forprefix
- A prefix for the folder that has to be found.maxIterations
- The maximum number of itarations this method shoud do.
If after them still no unique folder could be found, a IOException
is thrown.uniqueOutOf
- The range of random numbers to apply (0 - given value)IOException
- in case of an errorpublic static File createUniqueRandomFolder(File rootFolder, String prefix) throws IOException
This is a convenience method for createUniqueRandomFolder
and calls it with 10000 as maxIterations and 10000 as number range.
Note that this method might throw a IOException
if it will not find a unique name within 10000 iterations.
Note that the creation of the directory is not completely safe. This method is synchronized, but other processes could "steal" the unique filename.
rootFolder
- The rootFolder to find a unique subfolder forprefix
- A prefix for the folder that has to be found.IOException
- in case of an errorpublic static File getFile(File file, String... subDirs)
file
- The base directorysubDirs
- The subdirectories or filespublic static void writeTextFile(File file, String text, String encoding) throws IOException, FileNotFoundException, UnsupportedEncodingException
file
- The file to write the text totext
- The text to writeencoding
- The caracter set to use as file encoding (e.g. "UTF-8")IOException
- in case of an io errorFileNotFoundException
- if the file exists but is a directory
rather than a regular file, does not exist but cannot
be created, or cannot be opened for any other reasonUnsupportedEncodingException
- If the named encoding is not supportedpublic static String readTextFile(File f, String encoding) throws FileNotFoundException, IOException, UnsupportedEncodingException
f
- The file to read, maximum size 1 GBencoding
- The file encoding, e.g. "UTF-8"FileNotFoundException
- if the file was not foundIOException
- in case of an io errorUnsupportedEncodingException
- If the named encoding is not supportedpublic static String readTextFile(File f) throws FileNotFoundException, IOException
For other encodings, use readTextFile
.
f
- The file to read, maximum size 1 GBFileNotFoundException
- if the file was not foundIOException
- in case of an io errorpublic static void writeTextFile(File file, String text) throws IOException, FileNotFoundException, UnsupportedEncodingException
file
- The file to write the text totext
- The text to writeIOException
- in case of an io errorFileNotFoundException
- if the file exists but is a directory
rather than a regular file, does not exist but cannot
be created, or cannot be opened for any other reasonUnsupportedEncodingException
public static String readTextFile(InputStream in, String encoding) throws FileNotFoundException, IOException
InputStream
using
the given encoding.
This method does NOT close the input stream!
in
- The stream to read from. It will not be closed by this operation.encoding
- The charset used for decoding, e.g. "UTF-8"FileNotFoundException
IOException
public static String readTextFile(InputStream in) throws FileNotFoundException, IOException
InputStream
using
UTF-8 encoding.
This method does NOT close the input stream!
in
- The stream to read from. It will not be closed by this operation.FileNotFoundException
IOException
public static String getFileExtension(String fileName)
fileName
- A file name (might contain the full path) or null
.null
, if the given fileName
doesn't contain
a dot (".") or if the given fileName
is null
. Otherwise,
returns all AFTER the last dot.public static String getFileNameWithoutExtension(String fileName)
fileName
- A file name (might contain the full path) or null
.fileName
if no dot exists.
Returns null
, if the given fileName
is null
.public static File getTempDir()
Note, that you should better use #getUserTempDir()
in many situations
since there is solely one global temp directory in GNU/Linux and you might run into permissions trouble
and other collisions when using the global temp directory with a hardcoded static subdir.
#getUserTempDir()
public static File createUserTempDir(String prefix, String suffix) throws IOException
prefix
- null
or a prefix to be added before the user-name.suffix
- null
or a suffix to be added after the user-name.IOException
- if the directory does not exist and cannot be created.public static File getUserTempDir(String prefix, String suffix)
Since many operating systems (for example GNU/Linux and other unixes) use one global temp directory for all users, you might run into collisions when using hard-coded sub-directories within the temp dir. Permission problems can cause exceptions and multiple users sharing the same directory at the same time might even lead to heisenbugs. Therefore, this method encodes the user name into a subdirectory under the system's temp dir.
In order to prevent illegal directory names to be generated, this method encodes the user name (including the
pre- and suffixes passed) using a ParameterCoderMinusHex
which encodes all chars except
'0'...'9', 'A'...'Z', 'a'...'z', '.', '_' and '+'.
prefix
- null
or a prefix to be added before the user-name.suffix
- null
or a suffix to be added after the user-name.getTempDir()
,
createUserTempDir(String, String)
public static File getUserHome()
public static boolean compareInputStreams(InputStream in1, InputStream in2, long length) throws IOException
length
are consumed from the streams, no matter if their
contents are equal or not.in1
- the first InputStreamin2
- the second InputStreamlength
- how many bytes to read from each InputStreamIOException
- if an I/O error occurs while reading length
bytes
from one of the input streams.public static boolean compareInputStreams(InputStream in1, InputStream in2, long compareLength, long minimumReadLength) throws IOException
in1
- the first InputStreamin2
- the second InputStreamcompareLength
- how many bytes to compare before considering the stream
contents as equal.minimumReadLength
- how many bytes to read from each InputStream. This amount of
bytes is read from the stream, no matter if contents are equal or not.IOException
- if an I/O error occurs while reading length
bytes
from one of the input streams.public static boolean compareFiles(File f1, File f2) throws FileNotFoundException, IOException
f1
- the first filef2
- the second filetrue
if the files have same size and their contents are equal -
false
otherwise.FileNotFoundException
- If one of the files could not be found.IOException
- If reading one of the files failed.public static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException
sourceDirectory
- The source directorydestinationDirectory
- The destination directoryIOException
- in case of an errorpublic static void copyDirectory(File sourceDirectory, File destinationDirectory, FileFilter fileFilter) throws IOException
IOException
public static void copyResource(Class<?> sourceResClass, String sourceResName, String destinationFilename) throws IOException
This is a convenience method for copyResource(sourceResClass, sourceResName, new File(destinationFilename))
.
sourceResClass
- The class whose class loader to use. If the class
was loaded using the bootstrap class loaderClassloader.getSystemResourceAsStream
will be used. See Class.getResourceAsStream(String)
for details.sourceResName
- The name of the resourcedestinationFilename
- Where to copy the contents of the resourceIOException
- in case of an errorpublic static void copyResource(Class<?> sourceResClass, String sourceResName, File destinationFile) throws IOException
sourceResClass
- The class whose class loader to use. If the class
was loaded using the bootstrap class loaderClassloader.getSystemResourceAsStream
will be used. See Class.getResourceAsStream(String)
for details.sourceResName
- The name of the resourcedestinationFile
- Where to copy the contents of the resourceIOException
- in case of an errorpublic static void copyFile(File sourceFile, File destinationFile) throws IOException
sourceFile
- The source file to copydestinationFile
- To which file to copy the sourceIOException
- in case of an errorpublic static void copyFile(File sourceFile, File destinationFile, ProgressMonitor monitor) throws IOException
IOException
public static String addFinalSlash(String directory)
directory
- A directory nameFile.separator
public static void replaceTemplateVariables(File destinationFile, File templateFile, String characterSet, Map<?,?> variables) throws IOException
"${variable}"
.
All those variables will be replaced, for which a value has been passed in the map variables
.
Example:
*** Dear ${receipient.fullName}, this is a spam mail trying to sell you ${product.name} for a very cheap price. Best regards, ${sender.fullName} ***
variables
needs to contain values for these keys:
If a key is missing in the map, the variable will not be replaced but instead written as-is into the destination file (a warning will be logged).
destinationFile
- The file (absolute!) that shall be created out of the template.templateFile
- The template file to use. Must not be null
.characterSet
- The charset to use for the input and output file. Use null
for the default charset.variables
- This map defines what variable has to be replaced by what value. The
key is the variable name (without '$' and brackets '{', '}'!) and the value is the
value that will replace the variable in the output. This argument must not be null
.
In order to allow passing Properties
directly, this has been redefined as Map<?,?>
from version 1.3.0 on. Map entries with a key that is not of type String
or with a null
value are ignored. Values that are not of type String
are converted using the
toString()
method.IOException
public static String replaceTemplateVariables(String template, Map<?,?> variables)
"${variable}"
) with their values
passed in the map variables
.
Example:
*** Dear ${receipient.fullName}, this is a spam mail trying to sell you ${product.name} for a very cheap price. Best regards, ${sender.fullName} ***
variables
needs to contain values for these keys:
If a key is missing in the map, the variable will not be replaced but instead written as-is into the destination file (a warning will be logged).
template
- the input text containing variables (or not).variables
- This map defines what variable has to be replaced by what value. The
key is the variable name (without '$' and brackets '{', '}'!) and the value is the
value that will replace the variable in the output. This argument must not be null
.
In order to allow passing Properties
directly, this has been redefined as Map<?,?>
from version 1.3.0 on. Map entries with a key that is not of type String
or with a null
value are ignored. Values that are not of type String
are converted using the
toString()
method.public static void replaceTemplateVariables(Writer writer, Reader reader, Map<?,?> variables) throws IOException
"${variable}"
with their values
passed in the map variables
.
Example:
*** Dear ${receipient.fullName}, this is a spam mail trying to sell you ${product.name} for a very cheap price. Best regards, ${sender.fullName} ***
variables
needs to contain values for these keys:
If a key is missing in the map, the variable will not be replaced but instead written as-is into the destination file (a warning will be logged).
writer
- The writer to write the output to.reader
- The template file to use. Must not be null
.variables
- This map defines what variable has to be replaced by what value. The
key is the variable name (without '$' and brackets '{', '}'!) and the value is the
value that will replace the variable in the output. This argument must not be null
.
In order to allow passing Properties
directly, this has been redefined as Map<?,?>
from version 1.3.0 on. Map entries with a key that is not of type String
or with a null
value are ignored. Values that are not of type String
are converted using the
toString()
method.IOException
public static byte[] getBytesFromFile(File file) throws IOException
IOException
public static File createCollisionFile(File file)
public static String toPathString(java.nio.file.Path path)
public static long getLastModifiedNoFollow(File file)
public static long getLastModifiedNoFollow(java.nio.file.Path path)
public static void setLastModifiedNoFollow(File file, long lastModified)
public static void setLastModifiedNoFollow(java.nio.file.Path path, long lastModified)
Copyright © 2013-2014. All Rights Reserved.