TUM CCSM Commons

edu.tum.cs.commons.filesystem
Class FileSystemUtils

java.lang.Object
  extended by edu.tum.cs.commons.filesystem.FileSystemUtils

public class FileSystemUtils
extends java.lang.Object

File system utilities.

Version:
$Rev: 29722 $
Author:
Florian Deissenboeck, Benjamin Hummel, $Author: deissenb $
Rating:
GREEN Hash: C0A48F2C854364D0F04BB664D5A318A6

Field Summary
static java.nio.charset.Charset UTF8_CHARSET
          Charset for UTF-8.
static java.lang.String UTF8_ENCODING
          Encoding for UTF-8.
 
Constructor Summary
FileSystemUtils()
           
 
Method Summary
static java.io.InputStream autoDecompressStream(java.io.InputStream in)
          Transparently creates a stream for decompression if the provided stream is compressed.
static java.io.File canonize(java.io.File file)
          Deprecated. 
static java.lang.String canonize(java.lang.String path)
          Deprecated. 
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 java.io.File commonRoot(java.lang.Iterable<? extends java.io.File> files)
          Determines the root directory from a collection of files.
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 directory, 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 file)
          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 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 boolean isAbsolutePath(java.lang.String filename)
          Returns whether a filename represents an absolute path.
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 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 parent, java.lang.String... elements)
          This method is similar to the constructor File.File(File, String) but allows to define multiple child levels.
static java.lang.String normalizeSeparators(java.lang.String path)
          Replace platform dependent separator char with forward slashes to create system-independent paths.
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.lang.String encoding)
          Read file content into a string using the given encoding.
static java.lang.String readFileUTF8(java.io.File file)
          Read file content into a string using UTF-8 encoding.
static java.util.Properties readPropertiesFile(java.io.File propertiesFile)
          Reads properties from a properties file.
static java.lang.String readStream(java.io.InputStream input)
          Read input stream into string.
static java.lang.String readStream(java.io.InputStream input, java.lang.String encoding)
          Read input stream into string.
static java.lang.String readStreamUTF8(java.io.InputStream input)
          Read input stream into string.
static void renameFileTo(java.io.File file, java.io.File dest)
          Renames the given file and throws an exception if this fails.
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 void unjar(java.io.File jarFile, java.io.File targetDirectory)
          Extract a JAR file to a directory.
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 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.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

UTF8_ENCODING

public static final java.lang.String UTF8_ENCODING
Encoding for UTF-8.

See Also:
Constant Field Values

UTF8_CHARSET

public static final java.nio.charset.Charset UTF8_CHARSET
Charset for UTF-8.

Constructor Detail

FileSystemUtils

public FileSystemUtils()
Method Detail

copy

public static int copy(java.io.InputStream input,
                       java.io.OutputStream output)
                throws java.io.IOException
Copy an input stream to an output stream. This does not close the streams.

Parameters:
input - input stream
output - output stream
Returns:
number of bytes copied
Throws:
java.io.IOException - if an IO exception occurs.

copyFile

public static void copyFile(java.io.File sourceFile,
                            java.io.File targetFile)
                     throws java.io.IOException
Copy a file. This creates all necessary directories.

Throws:
java.io.IOException

copyFile

public static void copyFile(java.lang.String sourceFilename,
                            java.lang.String targetFilename)
                     throws java.io.IOException
Copy a file. This creates all necessary directories.

Throws:
java.io.IOException

copyFiles

public static int copyFiles(java.io.File sourceDirectory,
                            java.io.File targetDirectory,
                            java.io.FileFilter fileFilter)
                     throws java.io.IOException
Copy all files specified by a file filter from one directory to another. This automatically creates all necessary directories.

Parameters:
sourceDirectory - source directory
targetDirectory - target directory
fileFilter - filter to specify file types. If all files should be copied, use FileOnlyFilter.
Returns:
number of files copied
Throws:
java.io.IOException - if an exception occurs.

createJARFile

public static int createJARFile(java.io.File jarFile,
                                java.io.File directory,
                                java.io.FileFilter filter)
                         throws java.io.IOException
Create jar file from all files in a directory.

Parameters:
jarFile - jar file to create.
directory - source directory.
filter - filter to specify file types. If all files should be copied, use FileOnlyFilter.
Returns:
number of files added to the jar file
Throws:
java.io.IOException - if an exception occurs.

createRelativePath

public static java.lang.String createRelativePath(java.io.File path,
                                                  java.io.File relativeTo)
                                           throws java.io.IOException
Returns a string describing the relative path to the given directory. If there is no relative path, as the directories do not share a common parent, the absolute path is returned.

Parameters:
path - the path to convert to a relative path (must describe an existing directory)
relativeTo - the anchor (must describe an existing directory)
Returns:
a relative path
Throws:
java.io.IOException - if creation of canonical pathes fails.

deleteRecursively

public static void deleteRecursively(java.io.File directory)
Recursively delete directories and files. This method ignores the return value of delete(), i.e. if anything fails, some files might still exist.


deleteFile

public static void deleteFile(java.io.File file)
                       throws java.io.IOException
Deletes the given file and throws an exception if this fails.

Throws:
java.io.IOException
See Also:
File.delete()

renameFileTo

public static void renameFileTo(java.io.File file,
                                java.io.File dest)
                         throws java.io.IOException
Renames the given file and throws an exception if this fails.

Throws:
java.io.IOException
See Also:
File.renameTo(File)

mkdir

public static void mkdir(java.io.File dir)
                  throws java.io.IOException
Creates a directory and throws an exception if this fails.

Throws:
java.io.IOException
See Also:
File.mkdir()

mkdirs

public static void mkdirs(java.io.File dir)
                   throws java.io.IOException
Creates a directory and all required parent directories. Throws an exception if this fails.

Throws:
java.io.IOException
See Also:
File.mkdirs()

ensureDirectoryExists

public static void ensureDirectoryExists(java.io.File file)
                                  throws java.io.IOException
Checks if a directory exists. If not it creates the directory and all necessary parent directories.

Parameters:
file - the directory
Throws:
java.io.IOException - if directories couldn't be created.

ensureParentDirectoryExists

public static void ensureParentDirectoryExists(java.io.File file)
                                        throws java.io.IOException
Checks if the parent directory of a file exists. If not it creates the directory and all necessary parent directories.

Parameters:
file - the file
Throws:
java.io.IOException - if directories couldn't be created.

listFilesRecursively

public 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. The given directory itself is not included in the result.

This method knows nothing about (symbolic and hard) links, so care should be taken when traversing directories containing recursive links.

Parameters:
directory - the directory to start the search from.
Returns:
the list of files found (the order is determined by the file system).

listFilesRecursively

public 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. The given directory itself is not included in the result.

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.

Parameters:
directory - the directory to start the search from. If this is null or the directory does not exists, 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.
Returns:
the list of files found (the order is determined by the file system).

getFileExtension

public static java.lang.String getFileExtension(java.io.File file)
Returns the extension of the file.

Returns:
File extension, i.e. "java" for "FileSystemUtils.java", or 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.

newFile

public static java.io.File newFile(java.io.File parent,
                                   java.lang.String... elements)
This method is similar to the constructor File.File(File, String) but allows to define multiple child levels.

Parameters:
parent - parent file
elements - list of elements. If this is empty, the parent is returned.
Returns:
the new file.

readFile

public static java.lang.String readFile(java.io.File file)
                                 throws java.io.IOException
Read file content into a string using the default encoding for the platform. If the file starts with a UTF byte order mark (BOM), the encoding is ignored and the correct encoding based on this BOM is used for reading the file.

Throws:
java.io.IOException
See Also:
EByteOrderMark

readFileUTF8

public static java.lang.String readFileUTF8(java.io.File file)
                                     throws java.io.IOException
Read file content into a string using UTF-8 encoding. If the file starts with a UTF byte order mark (BOM), the encoding is ignored and the correct encoding based on this BOM is used for reading the file.

Throws:
java.io.IOException
See Also:
EByteOrderMark

readFile

public static java.lang.String readFile(java.io.File file,
                                        java.lang.String encoding)
                                 throws java.io.IOException,
                                        java.io.UnsupportedEncodingException
Read file content into a string using the given encoding. If the file starts with a UTF byte order mark (BOM), the encoding is ignored and the correct encoding based on this BOM is used for reading the file.

Throws:
java.io.IOException
java.io.UnsupportedEncodingException
See Also:
EByteOrderMark

unjar

public static void unjar(java.io.File jarFile,
                         java.io.File targetDirectory)
                  throws java.io.IOException
Extract a JAR file to a directory.

Parameters:
jarFile - jar file to extract
targetDirectory - target directory.
Throws:
java.io.IOException - if an exception occurs.

writeFile

public static void writeFile(java.io.File file,
                             java.lang.String content)
                      throws java.io.IOException
Write string to a file with the default encoding. This ensures all directories exist.

Throws:
java.io.IOException

writeFileUTF8

public static void writeFileUTF8(java.io.File file,
                                 java.lang.String content)
                          throws java.io.IOException
Write string to a file with UTF8 encoding. This ensures all directories exist.

Throws:
java.io.IOException

writeFile

public static void writeFile(java.io.File file,
                             java.lang.String content,
                             java.lang.String encoding)
                      throws java.io.IOException
Write string to a file. This ensures all directories exist.

Throws:
java.io.IOException

writeFileWithBOM

public static void writeFileWithBOM(java.io.File file,
                                    java.lang.String content,
                                    EByteOrderMark bom)
                             throws java.io.IOException
Write string to a file using a UTF encoding. The file will be prefixed with a byte-order mark. This ensures all directories exist.

Throws:
java.io.IOException

mergeTemplate

public static void mergeTemplate(java.io.File templateFile,
                                 java.io.File outFile,
                                 java.lang.Object... arguments)
                          throws java.io.IOException
Loads template file with a Format string, formats it and writes result to file.

Parameters:
templateFile - the template file with the format string
outFile - the target file, parent directories are created automatically.
arguments - the formatting arguments.
Throws:
java.io.IOException - if an IO exception occurs or the template file defines an illegal format.

mergeTemplate

public static java.io.InputStream mergeTemplate(java.io.InputStream inStream,
                                                java.lang.Object... arguments)
                                         throws java.io.IOException
Loads template file with a Format string, formats it and provides result as stream. No streams are closed by this method.

Parameters:
inStream - stream that provides the template format string
arguments - the formatting arguments.
Throws:
java.io.IOException - if an IOException occurs or the template file defines an illegal format.

readStream

public static java.lang.String readStream(java.io.InputStream input)
                                   throws java.io.IOException
Read input stream into string.

Throws:
java.io.IOException

readStreamUTF8

public static java.lang.String readStreamUTF8(java.io.InputStream input)
                                       throws java.io.IOException
Read input stream into string.

Throws:
java.io.IOException

readStream

public static java.lang.String readStream(java.io.InputStream input,
                                          java.lang.String encoding)
                                   throws java.io.IOException
Read input stream into string.

Throws:
java.io.IOException

readPropertiesFile

public static java.util.Properties readPropertiesFile(java.io.File propertiesFile)
                                               throws java.io.IOException
Reads properties from a properties file.

Throws:
java.io.IOException

commonRoot

public static java.io.File commonRoot(java.lang.Iterable<? extends java.io.File> files)
                               throws java.io.IOException
Determines the root directory from a collection of files. The root directory is the lowest common ancestor directory of the files in the directory tree.

This method does not require the input files to exist.

Parameters:
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.
Returns:
Root directory, or null, if the files do not have a common root directory.
Throws:
PreconditionException - 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 IOExceptions.

canonize

@Deprecated
public static java.lang.String canonize(java.lang.String path)
Deprecated. 

See canonize(File)


canonize

@Deprecated
public static java.io.File canonize(java.io.File file)
Deprecated. 

Creates a canonical path from a file path. This method wraps File.getCanonicalPath() and wraps IOExceptions thrown by it into AssertionErrors, since we expect this method not to throw IOExceptions.


autoDecompressStream

public static java.io.InputStream autoDecompressStream(java.io.InputStream in)
                                                throws java.io.IOException
Transparently creates a stream for decompression if the provided stream is compressed. Otherwise the stream is just handed through. Currently the following compression methods are supported:

Throws:
java.io.IOException

close

public static void close(java.io.Closeable closeable)
Convenience method for calling close(Closeable, ILogger) with a null-logger.


close

public 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. 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.


sort

public static void sort(java.util.List<java.io.File> files)
Compares files based on the lexical order of their fully qualified names. Files must not null.


normalizeSeparators

public static java.lang.String normalizeSeparators(java.lang.String path)
Replace platform dependent separator char with forward slashes to create system-independent paths.


extractJarFileFromJarURL

public static java.io.File extractJarFileFromJarURL(java.net.URL url)
Returns the JAR file for an URL with protocol 'jar'. If the protocol is not 'jar' an assertion error will be caused!


isAbsolutePath

public static boolean isAbsolutePath(java.lang.String filename)
Returns whether a filename represents an absolute path. This method returns the same result, independent on which operating system it gets executed. In contrast, the behavior of File.isAbsolute() is operating system specific.


safeRead

public static void safeRead(java.io.InputStream in,
                            byte[] data)
                     throws java.io.IOException,
                            java.io.EOFException
Reads bytes of data from the input stream into an array of bytes until the array is full. 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[]) may read less than the requested number of bytes, while this method ensures the data is complete.

Parameters:
in - the stream to read from.
data - the stream to read from.
Throws:
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.

safeRead

public static void safeRead(java.io.InputStream in,
                            byte[] data,
                            int offset,
                            int length)
                     throws java.io.IOException,
                            java.io.EOFException
Reads 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.

Parameters:
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.
Throws:
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.

TUM CCSM Commons

TUM CCSM Commons - 2.7