Package de.aristaflow.adept2.util
Class FileTools
java.lang.Object
de.aristaflow.adept2.util.FileTools
Utility class containing file-related helper methods, mostly concerning file
names and paths.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumThe compatibility of the file name. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringA string containing characters illegal for file names.static final StringThe characters which are not valid for a web server, which isILLEGAL_CHARSand some more characters.static final StringThe characters which are not valid as first or last character for a file on a web server. -
Method Summary
Modifier and TypeMethodDescriptionaddAllEntriesForClassPath(Path path, List<String> classPath, Logger logger) Adds all entries making up a classpath (JAR-files and directories) below the designated tree.static <C extends Closeable>
Cclose(C closeable) Deprecated, for removal: This API element is subject to removal in a future version.Use try-with-resources appropriately instead.static voidcloseQuietly(Closeable closeable) Deprecated, for removal: This API element is subject to removal in a future version.static voidcloseQuietly(Closeable... closeables) Deprecated, for removal: This API element is subject to removal in a future version.static voidcloseQuietly(Collection<? extends Closeable> closeables) Deprecated, for removal: This API element is subject to removal in a future version.static voidcopy(Path src, FilenameFilter filter, Path dest, CopyOption... options) Copies the designated source path to the designated destination path.static voidcreateFileWithParents(Path path) Creates the designated file including all parent directories.static FilecreateTempFile(File parent, String child, boolean directory) Creates a new temporary file or directory as child of the designated directory.static booleandeleteTree(Path tree, boolean includeRoot) Deletes the designated file path recursively, that is, if it is a directory, its complete contents will be deleted.static voidfileAccessible(File file, String usedFor) Checks whether the designated file can be accessed (written to).static StringfindFileAtDefaultLocation(String[] relativePaths, String[] absolutePaths) Tries to find one of the given relative or absolute paths and returns the first match.static URL[]getAllEntriesForClassPath(Path path, Logger logger) Gets all entries making up a classpath (JAR-files and directories) below the designated tree.static FilegetAppropriateSubDir(Collection<File> parentDirs, String subDir, boolean writable, boolean create, Logger logger) Gets the designated directory below the first of the designated parent directories which allow the desired (read or write) access.getAppropriateSubDirs(Collection<File> parentDirs, String subDir, boolean writable, boolean create, boolean firstOnly, Logger logger) Gets the designated sub directory below all of the designated parent directories which allow the desired (read or write) access.getAppropriateSubDirs(Collection<File> parentDirs, String subDir, Logger logger) Gets the designated sub directory below all of the designated parent directories which allow read access.static FileChecks if the designated path directory is a valid directory, it exists or can be created and returns it.static StringgetExtension(File file) Returns the filename's extension, i.e.static StringgetExtension(String filename) Returns the file's extension, i.e.static StringgetFileName(String path) Gets the file name of the designated path, i. e.static StringgetSimpleFileName(URL url) Gets the (simple) file name the designated URL refers to.static StringgetUniqueFileName(String fileName, Collection<String> allNames) Gets the designated file name as unique name with respect to the designated name collection.static FilegetWithoutExtension(File file) Returns the given file without the filename extension.static StringgetWithoutExtension(String path) Returns the given file path without the filename extension.static booleanhasExtension(File file, String extension) Tests whether the given file has the given extension.static booleanisWritable(File dir) Gets whether the designated directory can be written to, that is the directory itself (if it exists) or its closest existing ancestor (below which it can be created) is writable.static URLpathPropertyToURL(String classPath, Logger logger) Converts the designated classpath into an URL.static URL[]pathPropertyToURLs(List<String> classPaths, Logger logger) Converts the designated classpaths into an array of URLs by usingpathPropertyToURL(String, Logger).static Pathrelativise(String base, String target) Gets the path oftargetrelative to the designatedbase.static Pathrelativise(Path base, Path target) Gets the path oftargetrelative to the designatedbase.static booleanGets whether the two designatedfileURLs denote the same file/directory.static StringSanitises the name of a file (i.e.static Stringsanitise(String filename, String replacement, FileTools.Compatibility comp) Sanitises the name of a file (i.e.static byte[]toByteArray(File file) Reads a file into a new byte array.static FileConverts the designatedfileURL to aFile.static voidUnzips the designated zip file to the designated target folder.static booleanurlAccessible(URL url, Logger logger, boolean write) Checks (more or less reliable) whether the designated URL (directory) exists and can be accessed (for reading and/or writing).
-
Field Details
-
ILLEGAL_CHARS
A string containing characters illegal for file names. These have been determined on Windows XP and NTFS and should represent a superset of illegal characters across all or at least most OSes. -
ILLEGAL_CHARS_WEB
The characters which are not valid for a web server, which isILLEGAL_CHARSand some more characters. -
ILLEGAL_CHARS_WEB_START_END
The characters which are not valid as first or last character for a file on a web server.
-
-
Method Details
-
getExtension
Returns the filename's extension, i.e. the characters after the last dot. This method does not differentiate between "no extension" (the filename contains no dot) and "empty extension" (the dot is the final character in the filename). In both cases the empty string is returned.- Parameters:
file- the file for which to get the extension- Returns:
- the filename extension or the empty string
-
getExtension
Returns the file's extension, i.e. the characters after the last dot. This method does not differentiate between "no extension" (the filename contains no dot) and "empty extension" (the dot is the final character in the filename). In both cases the empty string is returned.- Parameters:
filename- the filename for which to get the extension- Returns:
- the filename extension or the empty string
-
hasExtension
Tests whether the given file has the given extension. The comparison is done in a case-insensitive way.- Parameters:
file- the file whose extension should be testedextension- the extension to test for- Returns:
- whether the given file has the given extension
-
getWithoutExtension
Returns the given file without the filename extension.- Parameters:
file- the file from which to remove the extension- Returns:
- the given file without the filename extension
-
getWithoutExtension
Returns the given file path without the filename extension.- Parameters:
path- the file path from which to remove the extension- Returns:
- the given file path without the filename extension
-
relativise
Gets the path oftargetrelative to the designatedbase.baseandtargetmust either both be absolute or both be relative.- Parameters:
base- The path as base for the relative path.target- The file or directory for which to determine a relative path relative tobase.- Returns:
- A relative path that resolves against
basetotarget. This will benullif no relative path is possible.
-
relativise
Gets the path oftargetrelative to the designatedbase.baseandtargetmust either both be absolute or both be relative.- Parameters:
base- The path as base for the relative path.target- The file or directory for which to determine a relative path relative tobase.- Returns:
- A relative path that resolves against
basetotarget. This will benullif no relative path is possible.
-
sanitise
Sanitises the name of a file (i.e. without any path) by replacing every illegal character with the given string.- Parameters:
filename- the filename to sanitisereplacement- the replacement for illegal characters- Returns:
- the sanitised filename
-
sanitise
Sanitises the name of a file (i.e. without any path) by replacing every illegal character with the designated replacement. The compatibility determines the illegal characters, i. e. a file on a web server must have a simpler name than that on a file system. This may even strip start and end characters.
If the replacement contains illegal characters, these will be replaced with_.- Parameters:
filename- The filename to sanitise. this must not benull.replacement- The replacement for illegal characters. If this is null, illegal characters will simply be removed.comp- TheFileTools.Compatibilityof the file name.- Returns:
- The sanitised filename.
- Throws:
IllegalArgumentException- If the designated file name becomes empty after replacing (and possibly stripping leading and trailing characters), anIllegalArgumentExceptionwill be thrown.
-
getFileName
Gets the file name of the designated path, i. e. removes the trailing path.- Parameters:
path- The path of which to get the file name. This may benull.- Returns:
- The file name of the designated path,
nullif the path isnull.
-
createTempFile
Creates a new temporary file or directory as child of the designated directory. Created files or directories will be deleted on normal exit of the JVM. If a temporary directory already exists, it will be used but it will not be deleted on exit. An existing file will not be used but anIOExceptionwill be thrown.- Parameters:
parent- The parent for the directory or file to be created. If this isnull, the system temp dir will be used as parent.child- The name of the temporary directory or file to be created. This must either be one directory or one file. Do not use several directories or a file and one or more directories. If you need this, call this method for each directory and the file.directory- Whether the temporary file system object is a directory (or a file).- Returns:
- The newly created file or directory.
- Throws:
IOException- If the temporary- directory/file cannot be created,
- directory already exists but it is not a directory,
- file already exists,
IOExceptionwill be thrown.
-
close
@Deprecated(since="15.0.0", forRemoval=true) public static <C extends Closeable> C close(C closeable) throws IOException Deprecated, for removal: This API element is subject to removal in a future version.Use try-with-resources appropriately instead.Closes the givenCloseableand returnsnull.- Type Parameters:
C-- Parameters:
closeable- theCloseableto be closed- Returns:
null- Throws:
IOException- ifCloseable.close()throws an exception
-
closeQuietly
Deprecated, for removal: This API element is subject to removal in a future version.Closes the givenCloseable, swallowing a potentialIOException.- Parameters:
closeable- theCloseableto be closed; may benull
-
closeQuietly
@Deprecated(since="15.0.0", forRemoval=true) public static void closeQuietly(Closeable... closeables) Deprecated, for removal: This API element is subject to removal in a future version.Closes the givenCloseables, swallowing a potentialIOException.- Parameters:
closeables- theCloseables to be closed; may benull
-
closeQuietly
@Deprecated(since="15.0.0", forRemoval=true) public static void closeQuietly(Collection<? extends Closeable> closeables) Deprecated, for removal: This API element is subject to removal in a future version.Closes the designatedCloseables, swallowing a potentialIOException.- Parameters:
closeables- theCloseables to be closed; may benull.
-
toByteArray
Reads a file into a new byte array. Be careful with large files!- Parameters:
file- the file whose content should be loaded into a byte array- Returns:
- the file's content in a byte array
- Throws:
IOException- if an I/O error occurs or the file was not found
-
pathPropertyToURLs
Converts the designated classpaths into an array of URLs by usingpathPropertyToURL(String, Logger).- Parameters:
classPaths- The classpaths to add as URLs or relative files.logger- The logger for log information created by this method.- Returns:
- All valid URLs contained in the designated class paths or an empty array in case the designated classpaths are null or empty.
- See Also:
-
pathPropertyToURL
Converts the designated classpath into an URL. An illegal URL is interpreted as local file. From this the canonical name is converted to a URL. If this also fails, the corresponding part of the classpath will be ignored.For instance, [/C:/Program%20Files/Java/jre1.5.0_07/lib/, /var/lib/security/local_policy.jar, http://aristaflow.de/adept2.jar] is converted to
- file://localhost/C:/Program%20Files/Java/jre1.5.0_07/lib/
- file://localhost/var/lib/security/local_policy.jar
- http://aristaflow.de/adept2.jar
- Parameters:
classPath- The classpath to as URL or relative files.logger- The logger for log information created by this method.- Returns:
- A valid URL contained in the designated class path null in case the designated classpath is null or cannot be transformed to an URL.
- See Also:
-
getDir
Checks if the designated path directory is a valid directory, it exists or can be created and returns it.- check if actually a string is supplied
- create a File object and check if the file exists (if required)
- check if it is a directory
- create the directory if appropriate
- Parameters:
path- The directory to check.create- Whether to create the directory if it does not exist.- Returns:
- The
File-instance representing the designated directory ornullin case the directory does not exist, cannot be accessed or cannot be created if appropriate.
-
getAppropriateSubDir
public static File getAppropriateSubDir(Collection<File> parentDirs, String subDir, boolean writable, boolean create, Logger logger) Gets the designated directory below the first of the designated parent directories which allow the desired (read or write) access. The directory can be created if required. If in all base directories the sub directory exists as file, exists as a directory but cannot be read from/written to or does not exist and cannot or should not be created,nullwill be returned.- Parameters:
parentDirs- The directories used as parent directories for the designated sub directory. This may containnullelements.subDir- The directory from which to read or to which to write to below the working or user home directory. This may but need not start with/.writable- Whether the directory needs to be writable.create- Whether to create the directory if it does not exist. Note that a newly created directory usually can be written, even if!writableis specified.logger- The logger for log information created by this method.- Returns:
- The designated sub directory below one of the designated parent directories if it can
be accessed in the desired way,
nullotherwise.
-
getAppropriateSubDirs
public static List<File> getAppropriateSubDirs(Collection<File> parentDirs, String subDir, Logger logger) Gets the designated sub directory below all of the designated parent directories which allow read access. The position of the sub directory in the returned collection corresponds to the position of the corresponding parent directory. If the sub directory exists as file, exists as directory but cannot be read from or does not exist in a specific parent directory,nullwill be stored at the corresponding position in the returned collection.- Parameters:
parentDirs- The directories used as parent directories for the designated sub directory. This may containnullelements.subDir- The directory from which to read below the designated parent directories. This may but need not start with/.logger- The logger for log information created by this method.- Returns:
- The designated sub directories below any of the designated parent directories if they
can be read from,
nullat the position in the collection corresponding to the position of the corresponding parent directory otherwise.
-
getAppropriateSubDirs
protected static List<File> getAppropriateSubDirs(Collection<File> parentDirs, String subDir, boolean writable, boolean create, boolean firstOnly, Logger logger) Gets the designated sub directory below all of the designated parent directories which allow the desired (read or write) access. The position of the sub directory in the returned collection corresponds to the position of the corresponding parent directory. Each sub directory can be created if required (viacreate). If the sub directory exists as file, exists as directory but cannot be read from/written to or does not exist and cannot or should not be created in a specific parent directory,nullwill be stored at the corresponding position in the returned collection.
If only one sub directory is relevant, setfirstOnlyto true. Then the first appropriate sub directory will be returned and the method will return immediately. If no such directory exists, the returned collection will contain just onenullentry.- Parameters:
parentDirs- The directories used as parent directories for the designated sub directory. This may containnullelements.subDir- The directory from which to read or to which to write to below the designated parent directories. This may but need not start with/.writable- Whether the sub directories need to be writable.create- Whether to create the sub directory if it does not exist. Note that a newly created directory usually can be written, even if!writableis specified. Also note that this may create sub directories below all parent directories. UsefirstOnlyto at most create one.firstOnly- Whether only the first valid sub directory is relevant. In this case the returned collection will only contain one entry. This will benullif the sub-directory is not available in any of the designated parent directories.logger- The logger for log information created by this method.- Returns:
- The designated sub directories below any of the designated parent directories if they
can be accessed in the desired way,
nullat the position in the collection corresponding to the position of the corresponding parent directory otherwise.
-
toFile
Converts the designatedfileURL to aFile.- Parameters:
url- The URL to convert; may benullor a non-fileURL.- Returns:
- The corresponding file or
nullif the URL isnullor not afileURL.
-
sameFile
Gets whether the two designatedfileURLs denote the same file/directory.- Parameters:
a- The first URL.b- The second URL.- Returns:
- Whether both URLs are
fileURLs denoting the same canonical file.
-
isWritable
Gets whether the designated directory can be written to, that is the directory itself (if it exists) or its closest existing ancestor (below which it can be created) is writable.- Parameters:
dir- The directory to check.- Returns:
- Whether the designated directory is writable or can be created in a writable location.
-
fileAccessible
Checks whether the designated file can be accessed (written to). If it does not exist, its parent directory is checked for whether the file can be created if required.- Parameters:
file- The file to check for whether it can be accessed (written to).usedFor- A string providing information for what the file is used for.- Throws:
IOException- If the designated file cannot be accessed (written to) or cannot be created, anIOExceptionwill be thrown.
-
createFileWithParents
Creates the designated file including all parent directories.- Parameters:
path- The file which to create.- Throws:
IOException- If there are problems creating the file or its parent directories, anIOExceptionwill be thrown.
-
deleteTree
Deletes the designated file path recursively, that is, if it is a directory, its complete contents will be deleted. If an exception occurs, deletion will continue and the exception will be thrown at the end.
NOTE: It will not be checked, whether the designated file path exists, therefore usingFiles.exists(Path, java.nio.file.LinkOption...)prior to this method is recommended.- Parameters:
tree- The tree which to delete recursively.includeRoot- Whether to also delete the designated tree root.- Returns:
- Whether recursive deletion has been completely successful.
- Throws:
IOException- If a problems occurs when deleting the designated tree, anIOExceptionwill be thrown.
-
getSimpleFileName
Gets the (simple) file name the designated URL refers to. This is the part after the last/. If the URL refers to a directory, this will be an empty string if the URL ends with/if not, it will be the name of the directory.- Parameters:
url- The URL from which to get the file name.- Returns:
- The file (or directory) name of the designated URL, which is the part after the last
/.nullif there is no/(should not occur).
-
urlAccessible
Checks (more or less reliable) whether the designated URL (directory) exists and can be accessed (for reading and/or writing).- Parameters:
url- The URL to check.logger- The logger for logging messages related to the accessibility of the designated URL. If this isnull, no messages will be logged.write- Whether the designated URL should also be accessible for writing.- Returns:
- Whether the designated URL can be accessed.
-
getAllEntriesForClassPath
Gets all entries making up a classpath (JAR-files and directories) below the designated tree.- Parameters:
path- The tree of which to determine all entries making up a classpath.logger- The logger where problems with iterating the tree be logged.- Returns:
- The classpath with the designated path and all files and directories below it.
-
addAllEntriesForClassPath
public static List<String> addAllEntriesForClassPath(Path path, List<String> classPath, Logger logger) Adds all entries making up a classpath (JAR-files and directories) below the designated tree. The designated path will not be part of the classpath.- Parameters:
path- The tree of which to determine all entries making up a classpath. This path will not be part of the classpath.classPath- The classpath where to add new classpath entries.logger- The logger where problems with iterating the tree be logged.- Returns:
- The classpaths where new entries have been added (the very same as the parameter
classPath).
-
findFileAtDefaultLocation
Tries to find one of the given relative or absolute paths and returns the first match. Relative paths are relative to the parent of the current working directory and are searched first.- Parameters:
relativePaths- Paths to search for, relative to the parent directory of the current working directory.absolutePaths- Absolute paths to search for.- Returns:
- An absolute paths to the first match
-
copy
public static void copy(Path src, FilenameFilter filter, Path dest, CopyOption... options) throws IOException Copies the designated source path to the designated destination path. If a file name filter is specified the complete directory tree will be copied but only files accepted by the filter. The target may only be a file in case the source is a file too. If source is a directory it will be copied recursively to the target directory.
UseStandardCopyOptions for replacing files in the destination and/or copying file attributes (e. g. timestamps).- Parameters:
src- The source file or directory which to copy, must not benull.filter- The filter a file from the source directory needs to match to be copied to the target directory.dest- The destination file or directory to which to copy, must not benull.options- The copy options like replacing files in the destination or copying file attributes.- Throws:
IOException- If there are problems transferring a file, anIOExceptionwill be thrown.
-
unzip
Unzips the designated zip file to the designated target folder.- Parameters:
zipFile- The zip file which to unzip.targetDir- The target folder to which to extract the content of the designated zip file.- Throws:
IOException- If there are problems reading from the zip file or writing to the target directory or the designated file is a directory or the target directory is a file, anIOExceptionwill be thrown.
-
getUniqueFileName
Gets the designated file name as unique name with respect to the designated name collection. Uniqueness is established by appending "-1" (or another number) between the file name and the file extension, e. g.fileName-1.txt. Understandably, the number is being incremented by one until the file name is unique.- Parameters:
fileName- The file name which should be unique.allNames- The file names already known. If this isnull, the file name will be returned unchanged.- Returns:
- The designated file name adapted so that it is unique with respect to the designated name collection.
-