Class IOHelper
java.lang.Object
net.simplace.core.service.IOHelper
Static helper methods for file and stream I/O: file names, copying and deleting files and directories, reading and
writing text, CSV and serialised objects, URLs and SMB network shares.
- Author:
- Andreas Enders
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classHelper class to determine the operating system the JVM runs on. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final PatternMatches a path segment followed by/../; used to resolve..in paths. -
Method Summary
Modifier and TypeMethodDescriptionstatic final voidaddLineToFile(File aFile, String aStringToAppend, int aMaxKBSizeOfFile) Appends a line (terminated by CR LF) to a text file.static URLConverts a string into a URL.static StringNormalises a path: backslashes are replaced by slashes anddir/../sequences are resolved.static FilecombineAndGZipFiles(String aAbsolutePath, List<File> aFilesForPattern, int aHeaderLinesToInclude) Concatenates several text files into one GZIP compressed file.static voidcopyDirectory(File aSourceDirectory, File aDestinationDirectory, boolean aCopySubFolders, boolean aOverwriteCopy) Copies the content of one directory to another one.static final voidCopies a file and creates the directory structure for the destination file if it does not exist yet.static final voidCopies the content of a directory recursively into a target directory.static final voidcopyFiles(File aSourceDir, File aDesDir, FileFilter aFileFilter, boolean aShouldOverwrite) Copies the content of a directory recursively into a target directory.static final voidcopyStream(InputStream aInputStream, OutputStream aOutputStream) Copies all data from an input stream to an output stream.static final voidcopyStream(Reader aReader, Writer aWriter) Copies all characters from a reader to a writer.static final voidCreates a directory including its parent directories if they do not exist yet.static booleancreateLockFile(File aDirectory) Creates a lock file.lockin a directory and keeps it open in a background thread for the lifetime of the JVM.static final booleanDeletes a directory with all its content.static final booleanDeletes a directory with all its content.static final booleandeleteDirContents(File dir, boolean goOnOnError) Deletes the complete content of a directory (files and subdirectories), but not the directory itself.static final booleandeleteDirContents(File aDir, String aExtension) Deletes the files of a directory (not of its subdirectories) with a given extension.static final booleandeleteDirContents(File aDir, String aExtension, long aOlderThanMillis) Deletes the files of a directory (not of its subdirectories) that match an extension and were last modified before a point in time.static final booleandeleteFile(File aFile) Deletes a file if it exists.static final voiddeleteFiles(File aFile) Deletes all files in a directory and its subdirectories.static voiddeleteFiles(File aSourceDir, FileFilter aFileFilter) Deletes all files and subdirectories (with their content) of a directory that are accepted by a filter.static final booleandeleteFiles(Collection<File> aFilesCollection) Deletes all files of a collection.static booleandoesFileExist(String aPath, boolean aSouldAcceptDirectories) Checks whether a file exists in the file system or as resource on the class path.static booleandoesPatternFit(String aFileName, String aPattern, boolean aIgnoreCase) Checks whether a file name matches a pattern.static booleandoesPatternFit(String aFileName, List<String> aPatternList, boolean aIgnoreCase) Checks whether a file name matches any of the given patterns.static final StringencodedStringFromInputStream(InputStream aInputStream) Reads all bytes of a stream and decodes them as UTF-8.static final StringencodedStringFromInputStream(InputStream aInputStream, String aEncoding) Reads all bytes of a stream and decodes them with the given encoding.static final voidfileFromInputStream(File aFile, InputStream aInputStream) Writes the content of an input stream to a file.static final voidfileToOutputStream(File aFile, OutputStream aOutputStream) Copies the content of a file to an output stream.static Collection<File> fillFileCollection(File aDirectory, boolean aIncludeDirectories, String aExtensionFilter) Returns all files of a directory tree.static Collection<File> fillFileCollection(File aDirectory, Collection<File> aFileCollection, boolean aIncludeDirectories) Adds all files of a directory tree to a collection.static Collection<File> fillFileCollection(File aDirectory, Collection<File> aFileCollection, String aExtensionFilter) Adds all files of a directory tree with a given extension to a collection.static <T extends Number>
voidfillWithZero(T[][] aValuesArray) Sets all elements of a number matrix to zero of the matching type.getAllFileNamesInDirectory(String aDirectory, String aExtension) Returns the names (without extension) of all files in a directory with a given extension.static byte[]getBytesFromFile(File aFile) Reads the complete content of a file into a byte array.static final Collection<File> getDirContents(File aDir, String aExtension, long aOlderThanMillis) Returns the files of a directory (not of its subdirectories) that match an extension and were last modified before a point in time.getDirectoriesOnly(File aDir, boolean aRecursive) Returns the subdirectories of a directory.static FilegetFile(Collection<File> aFileCollection, String aFileName) Finds a file with a given name (without path) in a collection.static final StringgetFileExtension(String aFullFileName) Returns the extension of a file name, i.e.static final StringgetFilename(String aFullFileName) Returns the name of a file without path and extension.static StringgetFilenameWithExtension(String aFullFileName) Returns the name of a file without path.Returns all files in a directory, optionally including the files in its subdirectories.getFilesForPattern(File aFile, String aRegexpPattern, boolean aShouldIncludeSubdirs, boolean aIgnoreCase) Returns all files in a directory whose name matches a regular expression, optionally including the files in its subdirectories.static longgetFileSize(File aFile, boolean aRecursive) Returns the size of a file.static StringgetFileSizeString(long aByte) Formats a size in bytes in a human readable form, e.g.getFilesWithExtension(File aDirectory, String aExtension) Returns the files of a directory (not of its subdirectories) with a given extension.getFilesWithExtension(File aDirectory, String aExtension, boolean aIncludeSubDirs) Returns the files of a directory with a given extension.static Stringstatic InputStreamgetInputStream(File aFile) Opens an input stream for a file.static final StringReturns the characters that are not allowed in file names, e.g.static Stringstatic final OutputStreamgetOutputStream(File aFile) Opens a buffered output stream for a file (buffer 65536 bytes, so small writes such as single output lines do not cause one system call each - important on network file systems).static StringgetRelativePath(File aFromDir, File aToFileOrDir) Calculates the relative path from a directory to a file or directory (using..where necessary).static StringgetTemporaryExecutionFilePath(String aFilePath) Returns a path for a new, empty file.static booleanstatic final booleanChecks whether a directory contains no files, neither directly nor in any subdirectory.static booleanisInDirectory(File aFile, File aDirectory) Checks whether a file lies inside a directory (at any depth).static final booleanisValidFilename(String aFilename) Checks whether a file name contains none of the invalid characters listed ingetInvalidFilenameCharacters().static final booleanisXMLFileExtension(String aExtension) Checks whether a file extension belongs to a (UTF-8 encoded) XML file:xml,aiform,aidocdeforaidoc, ignoring case.static final voidMoves (renames) a file and creates the directory structure for the destination file if it does not exist yet.static final StringplatformDefaultToUTF8(String aString) Repairs a string that was decoded with the wrong charset: its bytes in the platform default encoding are decoded again as UTF-8.static String[][]readCSVtoArray(File aFile, String aDivider, boolean aIncludeHeader) Reads a CSV file into a two-dimensional array (platform default encoding).static String[][]readCSVtoArray(InputStream aInputStream, String aDivider, boolean aIncludeHeader) Reads CSV data from a stream into a two-dimensional array (platform default encoding).static final StringReads the complete content of a text file with the platform default encoding.static final StringReads the complete content of a text file with the given encoding.static String[][]readFileToArray(File aFileData, String aDivider, Integer[] aLinesToRead) Reads a CSV-like text file into a two-dimensional array (platform default encoding), including the header line.static String[][]readFileToArray(File aFileData, String aDivider, Integer[] aLinesToRead, Integer aSkipHeaderLines) Reads a CSV-like text file into a two-dimensional array (platform default encoding).static final StringreadFirstCharsOfFile(File aFile, int aNumberOfChars) Reads the first characters of a text file (platform default encoding).static final StringreadLastLineOfFile(File aFile) Reads the last line of a text file (platform default encoding).readLinesOfFile(File aFile) Reads all lines of a text file with the platform default encoding.readLinesOfFile(File aFile, String aEncoding, Integer[] aLinesToRead) Reads lines of a text file.readLinesOfStream(InputStream aInputStream, Integer[] aLinesToRead, String encoding) Reads lines from a text stream.static final ObjectreadObjectFromFile(File aSourceFile) Reads a serialised object from a file.static String[][]readStreamToArray(InputStream aInputStream, String aDivider, String aEncoding) Reads CSV-like text from a stream into a two-dimensional array, including the header line.static ObjectresizeArray(Object oldArray, int newSize) Reallocates an array with a new size, and copies the contents of the old array to the new array.static final StringreturnValidFilename(String aUncheckedFilename) Removes characters that are not allowed in file names, including slashes and backslashes.static final StringreturnValidPath(String aUncheckedFilename) Removes characters that are not allowed in file names from a path:& < > ? " | % ! ^ ; , * # + ', line feeds and tabs.static voidsetAuthentication(String aUsername, String aPassword) Sets the credentials used for SMB network shares.static final StringBufferstringBufferFromInputStream(InputStream aInputStream) Reads the complete content of a stream as text (platform default encoding).static final StringBufferstringBufferFromInputStream(InputStream aInputStream, String aEncoding) Reads the complete content of a stream as text with the given encoding.static final voidstringBufferToOutputStream(StringBuffer aStringBuffer, OutputStream aOutputStream) Writes the content of a StringBuffer to an output stream with the platform default encoding.static final StringstringFromInputStream(InputStream aInputStream) Reads the complete content of a stream as text (platform default encoding).static final StringstringFromInputStream(InputStream aInputStream, String aEncoding) Reads the complete content of a stream as text with the given encoding.static final voidstringToFile(String aString, File aFile) Writes a string to a file (ISO-8859-1 on Linux, otherwise platform default encoding).static final voidstringToFile(String aString, File aFile, String aEncoding) Writes a string to a file in the given encoding.static final voidstringToOutputStream(String aString, OutputStream aOutputStream) Writes a string to an output stream with the platform default encoding.static final voidstringToOutputStream(String aString, OutputStream aOutputStream, String aEncoding) Writes a string to an output stream in the given encoding.static final voidstringToOutputStreamAndClose(String aString, OutputStream aOutputStream) Writes a string to an output stream and closes it.static final voidstringToOutputStreamAndClose(String aString, OutputStream aOutputStream, String aEncoding) Writes a string to an output stream in the given encoding and closes it.static URLCreates a URL from an absolute URL string, replacing the deprecated constructornew URL(String).static final StringUTF8ToPlatformDefault(String aString) Repairs a string that was decoded with the wrong charset: its UTF-8 bytes are decoded again with the platform default encoding.static <T> voidwriteArrayToFile(T[][] aSumOfCutValues, File aFile, String aSeperator) Writes a matrix to a text file.static final voidwriteLinesOfFile(Vector<String> aLinesVector, File aFile) Writes lines to a text file, each terminated by CR LF.static voidwriteObjectToFile(File aDestFile, Object aObject) Serialises an object into a file.
-
Field Details
-
PATH_BACK_PATTERN
Matches a path segment followed by/../; used to resolve..in paths.
-
-
Method Details
-
getFileExtension
-
getFilename
-
getFilenameWithExtension
-
getAllFileNamesInDirectory
Returns the names (without extension) of all files in a directory with a given extension. Subdirectories are not searched.- Parameters:
aDirectory- directory to searchaExtension- extension without dot, compared ignoring case- Returns:
- the file names without extension
-
writeObjectToFile
public static void writeObjectToFile(File aDestFile, Object aObject) throws FileNotFoundException, IOException Serialises an object into a file.- Parameters:
aDestFile- target fileaObject- object to write; must be serialisable- Throws:
FileNotFoundException- if the file cannot be createdIOException- if the object cannot be written- See Also:
-
readObjectFromFile
public static final Object readObjectFromFile(File aSourceFile) throws FileNotFoundException, IOException, Exception Reads a serialised object from a file.- Parameters:
aSourceFile- file to read- Returns:
- the deserialised object
- Throws:
FileNotFoundException- if the file does not existIOException- if the file cannot be readException- if the object cannot be deserialised, e.g. its class is not found- See Also:
-
copyFiles
Copies the content of a directory recursively into a target directory. Existing files are overwritten.- Parameters:
aSourceDir- directory to copyaDesDir- target directory; created if it does not exist- Throws:
IOException- if a file cannot be copied
-
copyFiles
public static final void copyFiles(File aSourceDir, File aDesDir, FileFilter aFileFilter, boolean aShouldOverwrite) throws IOException Copies the content of a directory recursively into a target directory. Only files and directories accepted by the filter are copied; filter and overwrite flag apply to the subdirectories as well.- Parameters:
aSourceDir- directory to copyaDesDir- target directory; created if it does not existaFileFilter- filter for the entries to copy, ornullfor allaShouldOverwrite- iftrue, existing files are overwritten- Throws:
IOException- if a file cannot be copied
-
copyDirectory
public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory, boolean aCopySubFolders, boolean aOverwriteCopy) throws IOException Copies the content of one directory to another one.- Parameters:
aSourceDirectory- directory to copyaDestinationDirectory- target directory; created if it does not existaCopySubFolders- iftrue, subdirectories are copied recursively, otherwise only filesaOverwriteCopy- iftrue, existing files are overwritten- Throws:
IOException- if a file cannot be copied
-
copyFile
public static final void copyFile(File aSourceFile, File aDestFile, boolean aShouldOverwrite) throws FileNotFoundException, IOException Copies a file and creates the directory structure for the destination file if it does not exist yet.- Parameters:
aSourceFile- file to copyaDestFile- target fileaShouldOverwrite- iftrue, an existing target file is replaced; otherwise nothing is copied if it exists- Throws:
FileNotFoundException- if the source file cannot be found or the target file cannot be createdIOException- if an error occurs while copying
-
moveFile
public static final void moveFile(File aSourceFile, File aDestFile, boolean aShouldOverwrite) throws FileNotFoundException, IOException Moves (renames) a file and creates the directory structure for the destination file if it does not exist yet. Whether the move succeeded is not checked.- Parameters:
aSourceFile- file to moveaDestFile- target fileaShouldOverwrite- iftrue, an existing target file is deleted first; otherwise nothing is moved if it exists- Throws:
FileNotFoundException- declared but not thrownIOException- if the target directory cannot be created or the existing target file cannot be deleted
-
addLineToFile
public static final void addLineToFile(File aFile, String aStringToAppend, int aMaxKBSizeOfFile) throws IOException Appends a line (terminated by CR LF) to a text file. If the file exceeds the maximum size, it is first copied to a backup file<name>_<yyyyMMddHHmm>.<extension>in the same directory and then overwritten.- Parameters:
aFile- file to write to; created if it does not existaStringToAppend- line to appendaMaxKBSizeOfFile- maximum file size in KB; 0 or less for no limit- Throws:
IOException- 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 reason
-
readFirstCharsOfFile
Reads the first characters of a text file (platform default encoding).- Parameters:
aFile- file to read fromaNumberOfChars- number of characters to read- Returns:
- a string of length aNumberOfChars; if the file is shorter, the rest is filled with
'\0' - Throws:
IOException- if the file does not exist or cannot be read
-
readLinesOfFile
public static final Vector<String> readLinesOfFile(File aFile, String aEncoding, Integer[] aLinesToRead) throws IOException Reads lines of a text file.- Parameters:
aFile- file to read from (seegetInputStream(File)for supported sources)aEncoding- character encoding of the fileaLinesToRead- indices of the lines to read (seereadLinesOfStream(InputStream, Integer[], String))- Returns:
- the lines read; empty if nothing could be read
- Throws:
IOException- if the file does not exist or cannot be read
-
readFile
Reads the complete content of a text file with the platform default encoding.- Parameters:
aFile- file to read from (seegetInputStream(File)for supported sources)- Returns:
- the file content
- Throws:
IOException- if the file does not exist or cannot be read
-
readFile
Reads the complete content of a text file with the given encoding.- Parameters:
aFile- file to read from (seegetInputStream(File)for supported sources)aEncoding- character encoding of the file- Returns:
- the file content
- Throws:
IOException- if the file does not exist or cannot be read
-
getInputStream
Opens an input stream for a file. Supported are:- plain files,
- GZIP files (name ending with
.gz), decompressed on the fly, - entries of ZIP files, given as
archive.zip/path/in/archive, - entries of GZIP compressed TAR files, given as
archive.tar.gz/path/in/archive, - files on SMB shares (
\\server\share,//server/shareorsmb://); on Linux and macOS the user is asked for credentials, - resources on the class path, if the file does not exist.
- Parameters:
aFile- file to open- Returns:
- the input stream, or
nullif a class path resource is not found - Throws:
IOException- if the stream cannot be opened
-
getOutputStream
Opens a buffered output stream for a file (buffer 65536 bytes, so small writes such as single output lines do not cause one system call each - important on network file systems). Missing parent directories are created. Files ending with.gzare compressed with GZIP. On Linux and macOS, files on SMB shares are written via jCIFS (the user is asked for credentials), asgetInputStream(File)reads them.Buffered data reaches the file only on
flush()orclose(), so the caller has to close the stream. Streams still open when the JVM exits are closed by a shutdown hook.- Parameters:
aFile- file to write- Returns:
- the output stream, or
nullif it cannot be opened (a warning is logged) - Throws:
IOException- declared but not thrown
-
readLinesOfFile
Reads all lines of a text file with the platform default encoding.- Parameters:
aFile- file to read from (seegetInputStream(File)for supported sources)- Returns:
- the lines of the file
- Throws:
IOException- if the file does not exist or cannot be read
-
readFileToArray
public static String[][] readFileToArray(File aFileData, String aDivider, Integer[] aLinesToRead, Integer aSkipHeaderLines) throws IOException Reads a CSV-like text file into a two-dimensional array (platform default encoding).- Parameters:
aFileData- file to read from (seegetInputStream(File)for supported sources)aDivider- column divider (used as regular expression)aLinesToRead- indices of the data lines to read, ornullfor all (seereadLinesOfStream(InputStream, Integer[], String))aSkipHeaderLines- number of lines to remove from the beginning, ornull- Returns:
- the content as rows and columns
- Throws:
IOException- if the file does not exist or cannot be read- See Also:
-
readFileToArray
public static String[][] readFileToArray(File aFileData, String aDivider, Integer[] aLinesToRead) throws IOException Reads a CSV-like text file into a two-dimensional array (platform default encoding), including the header line.- Parameters:
aFileData- file to read from (seegetInputStream(File)for supported sources)aDivider- column divider (used as regular expression)aLinesToRead- indices of the data lines to read, ornullfor all (seereadLinesOfStream(InputStream, Integer[], String))- Returns:
- the content as rows and columns
- Throws:
IOException- if the file does not exist or cannot be read
-
readLinesOfStream
public static final Vector<String> readLinesOfStream(InputStream aInputStream, Integer[] aLinesToRead, String encoding) throws IOException Reads lines from a text stream. The first line (header) is always read. The stream is closed afterwards.- Parameters:
aInputStream- stream to read fromaLinesToRead- ascending indices of the data lines to read after the header (the first data line has index 1), ornullfor all linesencoding- character encoding, or empty/nullfor the platform default- Returns:
- the header line followed by the selected lines, or
nullif aInputStream isnull - Throws:
IOException- if the stream cannot be read
-
readStreamToArray
public static String[][] readStreamToArray(InputStream aInputStream, String aDivider, String aEncoding) throws IOException Reads CSV-like text from a stream into a two-dimensional array, including the header line. The stream is closed afterwards.- Parameters:
aInputStream- stream to read fromaDivider- column divider (used as regular expression)aEncoding- character encoding, or empty/nullfor the platform default- Returns:
- the content as rows and columns
- Throws:
IOException- if the stream cannot be read
-
writeLinesOfFile
public static final void writeLinesOfFile(Vector<String> aLinesVector, File aFile) throws IOException Writes lines to a text file, each terminated by CR LF. An existing file is overwritten.- Parameters:
aLinesVector- lines to writeaFile- file to write to- Throws:
IOException- if the file cannot be written
-
readLastLineOfFile
Reads the last line of a text file (platform default encoding).- Parameters:
aFile- file to read from (seegetInputStream(File)for supported sources)- Returns:
- the last line, or an empty string if the file is empty
- Throws:
IOException- if the file does not exist or cannot be read
-
stringBufferFromInputStream
public static final StringBuffer stringBufferFromInputStream(InputStream aInputStream) throws IOException Reads the complete content of a stream as text (platform default encoding). The stream is closed afterwards.- Parameters:
aInputStream- stream to read from- Returns:
- the content
- Throws:
IOException- if the stream cannot be read
-
stringBufferFromInputStream
public static final StringBuffer stringBufferFromInputStream(InputStream aInputStream, String aEncoding) throws IOException Reads the complete content of a stream as text with the given encoding. The stream is closed afterwards.- Parameters:
aInputStream- stream to read fromaEncoding- character encoding- Returns:
- the content
- Throws:
IOException- if the stream cannot be read or the encoding is not supported
-
stringFromInputStream
Reads the complete content of a stream as text (platform default encoding). The stream is closed afterwards.- Parameters:
aInputStream- stream to read from- Returns:
- the content
- Throws:
IOException- if the stream cannot be read
-
stringFromInputStream
public static final String stringFromInputStream(InputStream aInputStream, String aEncoding) throws IOException Reads the complete content of a stream as text with the given encoding. The stream is closed afterwards.- Parameters:
aInputStream- stream to read fromaEncoding- character encoding- Returns:
- the content
- Throws:
IOException- if the stream cannot be read or the encoding is not supported
-
encodedStringFromInputStream
public static final String encodedStringFromInputStream(InputStream aInputStream, String aEncoding) throws IOException Reads all bytes of a stream and decodes them with the given encoding. The stream is closed afterwards.- Parameters:
aInputStream- stream to read fromaEncoding- character encoding- Returns:
- the decoded content
- Throws:
IOException- if the stream cannot be read or the encoding is not supported
-
encodedStringFromInputStream
public static final String encodedStringFromInputStream(InputStream aInputStream) throws IOException Reads all bytes of a stream and decodes them as UTF-8. The stream is closed afterwards.- Parameters:
aInputStream- stream to read from- Returns:
- the decoded content
- Throws:
IOException- if the stream cannot be read
-
platformDefaultToUTF8
Repairs a string that was decoded with the wrong charset: its bytes in the platform default encoding are decoded again as UTF-8.- Parameters:
aString- string to convert- Returns:
- the re-decoded string
- Throws:
IOException- if UTF-8 is not supported (never happens)
-
isXMLFileExtension
Checks whether a file extension belongs to a (UTF-8 encoded) XML file:xml,aiform,aidocdeforaidoc, ignoring case.- Parameters:
aExtension- extension without dot- Returns:
trueif it is an XML file extension
-
UTF8ToPlatformDefault
Repairs a string that was decoded with the wrong charset: its UTF-8 bytes are decoded again with the platform default encoding.- Parameters:
aString- string to convert- Returns:
- the re-decoded string
- Throws:
IOException- if UTF-8 is not supported (never happens)
-
stringToOutputStream
public static final void stringToOutputStream(String aString, OutputStream aOutputStream) throws IOException Writes a string to an output stream with the platform default encoding. The stream is flushed but not closed.- Parameters:
aString- text to writeaOutputStream- stream to write to- Throws:
IOException- if writing fails
-
stringBufferToOutputStream
public static final void stringBufferToOutputStream(StringBuffer aStringBuffer, OutputStream aOutputStream) throws IOException Writes the content of a StringBuffer to an output stream with the platform default encoding. The stream is flushed but not closed.- Parameters:
aStringBuffer- text to writeaOutputStream- stream to write to- Throws:
IOException- if writing fails
-
stringToOutputStreamAndClose
public static final void stringToOutputStreamAndClose(String aString, OutputStream aOutputStream) throws IOException Writes a string to an output stream and closes it. On Linux ISO-8859-1 is used, otherwise the platform default encoding.- Parameters:
aString- text to writeaOutputStream- stream to write to- Throws:
IOException- if writing fails
-
stringToOutputStream
public static final void stringToOutputStream(String aString, OutputStream aOutputStream, String aEncoding) throws IOException Writes a string to an output stream in the given encoding. The stream is flushed but not closed.- Parameters:
aString- text to writeaOutputStream- stream to write toaEncoding- character encoding, or empty/nullfor the platform default- Throws:
IOException- if writing fails or the encoding is not supported
-
stringToOutputStreamAndClose
public static final void stringToOutputStreamAndClose(String aString, OutputStream aOutputStream, String aEncoding) throws IOException Writes a string to an output stream in the given encoding and closes it.- Parameters:
aString- text to writeaOutputStream- stream to write toaEncoding- character encoding, or empty/nullfor the default (seestringToOutputStreamAndClose(String, OutputStream))- Throws:
IOException- if writing fails or the encoding is not supported
-
stringToFile
public static final void stringToFile(String aString, File aFile, String aEncoding) throws IOException Writes a string to a file in the given encoding. An existing file is overwritten; missing directories are created. Files ending with.gzare compressed (seegetOutputStream(File)).- Parameters:
aString- text to writeaFile- file to write toaEncoding- character encoding, or empty/nullfor the default- Throws:
IOException- if writing fails
-
stringToFile
Writes a string to a file (ISO-8859-1 on Linux, otherwise platform default encoding). An existing file is overwritten; missing directories are created. Files ending with.gzare compressed (seegetOutputStream(File)).- Parameters:
aString- text to writeaFile- file to write to- Throws:
IOException- if writing fails
-
fileToOutputStream
public static final void fileToOutputStream(File aFile, OutputStream aOutputStream) throws IOException Copies the content of a file to an output stream. The output stream is flushed but not closed.- Parameters:
aFile- file to readaOutputStream- stream to write to- Throws:
IOException- if reading or writing fails
-
fileFromInputStream
public static final void fileFromInputStream(File aFile, InputStream aInputStream) throws IOException Writes the content of an input stream to a file. Missing directories are created; both streams are closed.- Parameters:
aFile- file to write toaInputStream- stream to read from- Throws:
IOException- if reading or writing fails
-
copyStream
public static final void copyStream(InputStream aInputStream, OutputStream aOutputStream) throws IOException Copies all data from an input stream to an output stream. The streams are not closed, except when an error occurs.- Parameters:
aInputStream- stream to read fromaOutputStream- stream to write to; flushed at the end- Throws:
IOException- if reading or writing fails; both streams are closed in this case
-
copyStream
Copies all characters from a reader to a writer. The reader and writer are not closed, except when an error occurs.- Parameters:
aReader- reader to read fromaWriter- writer to write to; flushed at the end- Throws:
IOException- if reading or writing fails; both are closed in this case
-
createDir
Creates a directory including its parent directories if they do not exist yet.- Parameters:
aDir- directory to create- Throws:
IOException- if a file with the same name exists or the directory cannot be created
-
deleteFile
Deletes a file if it exists.- Parameters:
aFile- file to delete- Returns:
trueif the file was deleted or did not exist
-
getFiles
Returns all files in a directory, optionally including the files in its subdirectories. Directories themselves are not returned.- Parameters:
aFile- directory to searchaShouldIncludeSubdirs- iftrue, subdirectories are searched recursively- Returns:
- the files; empty if aFile is not an existing directory
-
getFilesForPattern
public static final List<File> getFilesForPattern(File aFile, String aRegexpPattern, boolean aShouldIncludeSubdirs, boolean aIgnoreCase) Returns all files in a directory whose name matches a regular expression, optionally including the files in its subdirectories. Directories themselves are not returned.- Parameters:
aFile- directory to searchaRegexpPattern- regular expression the file name (without path) must match; empty for all filesaShouldIncludeSubdirs- iftrue, subdirectories are searched recursivelyaIgnoreCase- iftrue, the pattern is matched ignoring case- Returns:
- the matching files; empty if aFile is not an existing directory
-
deleteFiles
Deletes all files in a directory and its subdirectories. The directories themselves are not deleted.- Parameters:
aFile- directory whose files are deleted- Throws:
IOException- if a file cannot be deleted
-
deleteFiles
Deletes all files and subdirectories (with their content) of a directory that are accepted by a filter. Errors are ignored.- Parameters:
aSourceDir- directory whose entries are deletedaFileFilter- filter for the entries to delete, ornullfor all
-
deleteFiles
Deletes all files of a collection. Stops at the first file that cannot be deleted.- Parameters:
aFilesCollection- files to delete- Returns:
trueif all files were deleted
-
deleteDir
Deletes a directory with all its content. If a file is given, it is deleted. Stops at the first error.- Parameters:
dir- directory or file to delete- Returns:
trueif everything was deleted
-
deleteDir
Deletes a directory with all its content. If a file is given, it is deleted.- Parameters:
dir- directory or file to deletegoOnWithError- iftrue, deletion continues with the remaining entries after an error- Returns:
trueif the directory itself was deleted
-
isEmpty
Checks whether a directory contains no files, neither directly nor in any subdirectory.- Parameters:
aDirectory- directory to check- Returns:
trueif the directory tree contains no files;falseif aDirectory is a file
-
deleteDirContents
Deletes the complete content of a directory (files and subdirectories), but not the directory itself.- Parameters:
dir- directory to emptygoOnOnError- iftrue, deletion continues with the remaining entries after an error- Returns:
trueif all entries were deleted (also for an empty or missing directory),falseif an entry could not be deleted
-
deleteDirContents
Deletes the files of a directory (not of its subdirectories) that match an extension and were last modified before a point in time. The directory itself is not deleted.- Parameters:
aDir- directory whose files are deletedaExtension- extension without dot (ignoring case), ornullfor all filesaOlderThanMillis- only files last modified before this time (milliseconds since 1970) are deleted; negative for all- Returns:
falseif a file could not be deleted; otherwise whether the directory exists- See Also:
-
getDirContents
public static final Collection<File> getDirContents(File aDir, String aExtension, long aOlderThanMillis) Returns the files of a directory (not of its subdirectories) that match an extension and were last modified before a point in time.- Parameters:
aDir- directory to searchaExtension- extension without dot (ignoring case), ornullfor all filesaOlderThanMillis- only files last modified before this time (milliseconds since 1970) are returned; negative for all- Returns:
- the matching files; empty if aDir is not a directory
-
getDirectoriesOnly
Returns the subdirectories of a directory. In recursive mode only the leaf directories (directories without subdirectories) are returned. If aDir itself has no subdirectories (or in non-recursive mode never contains any processed in recursion), aDir itself is added to the result.- Parameters:
aDir- directory to searchaRecursive- iftrue, the leaf directories of the whole tree are returned; otherwise the direct subdirectories- Returns:
- the directories found
-
deleteDirContents
Deletes the files of a directory (not of its subdirectories) with a given extension. The directory itself is not deleted.- Parameters:
aDir- directory whose files are deletedaExtension- extension without dot, compared ignoring case- Returns:
falseif a file could not be deleted; otherwise whether the directory exists
-
returnValidFilename
-
returnValidPath
Removes characters that are not allowed in file names from a path:& < > ? " | % ! ^ ; , * # + ', line feeds and tabs. Backslashes are replaced by slashes and double spaces by single spaces. Note that colons are kept (drive letters).If you add or remove characters, also change
isValidFilename(String)andgetInvalidFilenameCharacters().- Parameters:
aUncheckedFilename- path to clean- Returns:
- the cleaned path
-
isValidFilename
Checks whether a file name contains none of the invalid characters listed ingetInvalidFilenameCharacters(). Only pass the file name without path.If you add or remove characters, also change
returnValidPath(String)andgetInvalidFilenameCharacters().- Parameters:
aFilename- file name to check- Returns:
trueif the file name is valid
-
getInvalidFilenameCharacters
Returns the characters that are not allowed in file names, e.g. for error messages.If you add or remove characters, also change
returnValidPath(String)andisValidFilename(String).- Returns:
- the invalid characters, separated by spaces
-
getFileSizeString
Formats a size in bytes in a human readable form, e.g.1.5 MB.- Parameters:
aByte- size in bytes- Returns:
- the formatted size with unit (Byte, KB, MB or GB)
-
getHostNameOfLocalSystem
- Returns:
- the host name of the local system
- Throws:
UnknownHostException- if the local host name cannot be resolved
-
getIPOfLocalSystem
- Returns:
- the IP address of the local system in dotted format
- Throws:
UnknownHostException- if the local host name cannot be resolved
-
getTemporaryExecutionFilePath
Returns a path for a new, empty file. If a file with the given path exists, it is deleted; if it cannot be deleted (e.g. because it is opened by another program), the name<name>~n.<ext>is tried instead.- Parameters:
aFilePath- desired file path- Returns:
- the absolute path of the created empty file
- Throws:
IOException- if the file cannot be created
-
doesPatternFit
public static boolean doesPatternFit(String aFileName, List<String> aPatternList, boolean aIgnoreCase) Checks whether a file name matches any of the given patterns.- Parameters:
aFileName- file name to checkaPatternList- patterns (seedoesPatternFit(String, String, boolean))aIgnoreCase- iftrue, case is ignored- Returns:
trueif at least one pattern matches
-
doesPatternFit
Checks whether a file name matches a pattern. The pattern is a regular expression in which*is additionally replaced by.*, so simple wildcards like*.xmlwork (note that.still matches any character).- Parameters:
aFileName- file name to checkaPattern- patternaIgnoreCase- iftrue, case is ignored- Returns:
trueif the whole file name matches
-
getRelativePath
Calculates the relative path from a directory to a file or directory (using..where necessary). Paths are compared ignoring case.- Parameters:
aFromDir- directory the path starts fromaToFileOrDir- target file or directory- Returns:
- the relative path with the system file separator
- Throws:
IOException- if the canonical paths cannot be determined or the paths have no common parent directory
-
fillFileCollection
public static Collection<File> fillFileCollection(File aDirectory, Collection<File> aFileCollection, boolean aIncludeDirectories) Adds all files of a directory tree to a collection.- Parameters:
aDirectory- root directoryaFileCollection- collection the files are added toaIncludeDirectories- iftrue, the directories are added as well- Returns:
- aFileCollection
-
fillFileCollection
public static Collection<File> fillFileCollection(File aDirectory, Collection<File> aFileCollection, String aExtensionFilter) Adds all files of a directory tree with a given extension to a collection. Directories are not added.- Parameters:
aDirectory- root directoryaFileCollection- collection the files are added toaExtensionFilter- only files whose name ends with this string are added; empty ornullfor all files- Returns:
- aFileCollection
-
fillFileCollection
public static Collection<File> fillFileCollection(File aDirectory, boolean aIncludeDirectories, String aExtensionFilter) Returns all files of a directory tree.- Parameters:
aDirectory- root directoryaIncludeDirectories- iftrue, directories are included as well (only if no extension filter is given)aExtensionFilter- only files whose name ends with this string are returned; empty ornullfor all files- Returns:
- a new collection with the files
-
getFileSize
Returns the size of a file. For a directory, the sizes of the files in it are added.- Parameters:
aFile- file or directoryaRecursive- iftrue, the files in subdirectories are included- Returns:
- the size in bytes
-
getFilesWithExtension
Returns the files of a directory (not of its subdirectories) with a given extension.- Parameters:
aDirectory- directory in which to searchaExtension- extension without dot, compared ignoring case- Returns:
- the matching files; empty if aDirectory is not a directory
-
getFilesWithExtension
public static ArrayList<File> getFilesWithExtension(File aDirectory, String aExtension, boolean aIncludeSubDirs) Returns the files of a directory with a given extension.- Parameters:
aDirectory- directory in which to searchaExtension- extension without dot, compared ignoring caseaIncludeSubDirs- iftrue, subdirectories are searched recursively- Returns:
- the matching files; empty if aDirectory is not a directory
-
getBytesFromFile
Reads the complete content of a file into a byte array.- Parameters:
aFile- file to read (seegetInputStream(File)for supported sources)- Returns:
- the content of the file
- Throws:
IOException- if the file cannot be read completelyIllegalArgumentException- if the file length is more than Integer.MAX_VALUE
-
isInDirectory
Checks whether a file lies inside a directory (at any depth). The paths are compared as given, not canonically.- Parameters:
aFile- file or directory to checkaDirectory- directory- Returns:
trueif aFile is aDirectory or lies below it
-
createLockFile
Creates a lock file.lockin a directory and keeps it open in a background thread for the lifetime of the JVM. An existing lock file is deleted first; if that fails (e.g. because another process holds it), the directory counts as locked.- Parameters:
aDirectory- directory to lock- Returns:
trueif the lock was created,falseif an existing lock file could not be deleted
-
getFile
Finds a file with a given name (without path) in a collection.- Parameters:
aFileCollection- files to searchaFileName- file name to look for (case sensitive)- Returns:
- the first matching file, or
nullif there is none
-
toURL
Creates a URL from an absolute URL string, replacing the deprecated constructornew URL(String). UnlikeURI.create(String), spaces and backslashes (as in Windows paths) are accepted: they are encoded resp. converted to slashes.- Parameters:
aURL- the URL string, e.g.http://simplace.net/dtd/OM_18.rdf- Returns:
- the URL
- Throws:
MalformedURLException- if the string isnull, not absolute (no protocol), has an unknown protocol or is no valid URL
-
checkURL
Converts a string into a URL. Local paths (starting with a file system root) become file URLs; strings without protocol getftp://,gopher://orhttp://prepended if they look like a host name. Otherwise the string is taken as file or directory (withindex.html/index.htm) or as class path resource. A warning is shown (seeFWClientContext.showWarning(String)) fornullor invalid URLs.- Parameters:
aURL- string to convert- Returns:
- the URL, or
nullif it cannot be determined
-
doesFileExist
Checks whether a file exists in the file system or as resource on the class path.- Parameters:
aPath- path to checkaSouldAcceptDirectories- iftrue, directories count as existing files- Returns:
trueif the file exists
-
readCSVtoArray
public static String[][] readCSVtoArray(File aFile, String aDivider, boolean aIncludeHeader) throws IOException Reads a CSV file into a two-dimensional array (platform default encoding).- Parameters:
aFile- file to read (seegetInputStream(File)for supported sources)aDivider- column divideraIncludeHeader- iftrue, the header line is included as first row- Returns:
- the content as rows and columns
- Throws:
IOException- if the file cannot be read- See Also:
-
readCSVtoArray
public static String[][] readCSVtoArray(InputStream aInputStream, String aDivider, boolean aIncludeHeader) throws IOException Reads CSV data from a stream into a two-dimensional array (platform default encoding). The number of columns is taken from the first row; surplus values in later rows are ignored, missing values arenull. The stream is closed afterwards.- Parameters:
aInputStream- stream to readaDivider- column divider (seeStringHelper.getListFromString(String, String, boolean, boolean))aIncludeHeader- iftrue, the header line is included as first row- Returns:
- the trimmed values as rows and columns
- Throws:
IOException- if the stream cannot be read
-
resizeArray
-
writeArrayToFile
public static <T> void writeArrayToFile(T[][] aSumOfCutValues, File aFile, String aSeperator) throws IOException Writes a matrix to a text file.- Type Parameters:
T- element type- Parameters:
aSumOfCutValues- matrix to writeaFile- file to write toaSeperator- separator between the values- Throws:
IOException- if the file cannot be written- See Also:
-
fillWithZero
Sets all elements of a number matrix to zero of the matching type.- Type Parameters:
T- number type- Parameters:
aValuesArray- matrix to fill; Double, Integer and Long matrices are supported
-
setAuthentication
-
cleanPath
-
hasAuthentication
public static boolean hasAuthentication()- Returns:
trueif a user name for SMB network shares has been set
-
combineAndGZipFiles
public static File combineAndGZipFiles(String aAbsolutePath, List<File> aFilesForPattern, int aHeaderLinesToInclude) throws IOException Concatenates several text files into one GZIP compressed file. The header lines are taken from the first file only; they are removed from all following files.- Parameters:
aAbsolutePath- path of the target file;.gzis appended if missingaFilesForPattern- files to combine, in this orderaHeaderLinesToInclude- number of header lines at the beginning of each file- Returns:
- the compressed target file
- Throws:
IOException- if a file cannot be read or written
-