Class IOHelper

java.lang.Object
net.simplace.core.service.IOHelper

public final class IOHelper extends Object
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
  • Field Details

    • PATH_BACK_PATTERN

      public static final Pattern PATH_BACK_PATTERN
      Matches a path segment followed by /../; used to resolve .. in paths.
  • Method Details

    • getFileExtension

      public static final String getFileExtension(String aFullFileName)
      Returns the extension of a file name, i.e. the part after the last dot.
      Parameters:
      aFullFileName - file name, optionally with path
      Returns:
      the extension without dot, or an empty string if there is no dot
    • getFilename

      public static final String getFilename(String aFullFileName)
      Returns the name of a file without path and extension.
      Parameters:
      aFullFileName - file name, optionally with path
      Returns:
      the file name without path and extension; the whole file name if it has no extension
    • getFilenameWithExtension

      public static String getFilenameWithExtension(String aFullFileName)
      Returns the name of a file without path. Both slashes and backslashes are recognised as path separators.
      Parameters:
      aFullFileName - file name, optionally with path
      Returns:
      the file name with extension
    • getAllFileNamesInDirectory

      public static final Set<String> getAllFileNamesInDirectory(String aDirectory, String aExtension)
      Returns the names (without extension) of all files in a directory with a given extension. Subdirectories are not searched.
      Parameters:
      aDirectory - directory to search
      aExtension - 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 file
      aObject - object to write; must be serialisable
      Throws:
      FileNotFoundException - if the file cannot be created
      IOException - 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 exist
      IOException - if the file cannot be read
      Exception - if the object cannot be deserialised, e.g. its class is not found
      See Also:
    • copyFiles

      public static final void copyFiles(File aSourceDir, File aDesDir) throws IOException
      Copies the content of a directory recursively into a target directory. Existing files are overwritten.
      Parameters:
      aSourceDir - directory to copy
      aDesDir - 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 copy
      aDesDir - target directory; created if it does not exist
      aFileFilter - filter for the entries to copy, or null for all
      aShouldOverwrite - if true, 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 copy
      aDestinationDirectory - target directory; created if it does not exist
      aCopySubFolders - if true, subdirectories are copied recursively, otherwise only files
      aOverwriteCopy - if true, 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 copy
      aDestFile - target file
      aShouldOverwrite - if true, 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 created
      IOException - 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 move
      aDestFile - target file
      aShouldOverwrite - if true, an existing target file is deleted first; otherwise nothing is moved if it exists
      Throws:
      FileNotFoundException - declared but not thrown
      IOException - 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 exist
      aStringToAppend - line to append
      aMaxKBSizeOfFile - 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

      public static final String readFirstCharsOfFile(File aFile, int aNumberOfChars) throws IOException
      Reads the first characters of a text file (platform default encoding).
      Parameters:
      aFile - file to read from
      aNumberOfChars - 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 (see getInputStream(File) for supported sources)
      aEncoding - character encoding of the file
      aLinesToRead - indices of the lines to read (see readLinesOfStream(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

      public static final String readFile(File aFile) throws IOException
      Reads the complete content of a text file with the platform default encoding.
      Parameters:
      aFile - file to read from (see getInputStream(File) for supported sources)
      Returns:
      the file content
      Throws:
      IOException - if the file does not exist or cannot be read
    • readFile

      public static final String readFile(File aFile, String aEncoding) throws IOException
      Reads the complete content of a text file with the given encoding.
      Parameters:
      aFile - file to read from (see getInputStream(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

      public static InputStream getInputStream(File aFile) throws IOException
      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/share or smb://); 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 null if a class path resource is not found
      Throws:
      IOException - if the stream cannot be opened
    • getOutputStream

      public static final OutputStream getOutputStream(File aFile) throws IOException
      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 .gz are compressed with GZIP. On Linux and macOS, files on SMB shares are written via jCIFS (the user is asked for credentials), as getInputStream(File) reads them.

      Buffered data reaches the file only on flush() or close(), 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 null if it cannot be opened (a warning is logged)
      Throws:
      IOException - declared but not thrown
    • readLinesOfFile

      public static final Vector<String> readLinesOfFile(File aFile) throws IOException
      Reads all lines of a text file with the platform default encoding.
      Parameters:
      aFile - file to read from (see getInputStream(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 (see getInputStream(File) for supported sources)
      aDivider - column divider (used as regular expression)
      aLinesToRead - indices of the data lines to read, or null for all (see readLinesOfStream(InputStream, Integer[], String))
      aSkipHeaderLines - number of lines to remove from the beginning, or null
      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 (see getInputStream(File) for supported sources)
      aDivider - column divider (used as regular expression)
      aLinesToRead - indices of the data lines to read, or null for all (see readLinesOfStream(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 from
      aLinesToRead - ascending indices of the data lines to read after the header (the first data line has index 1), or null for all lines
      encoding - character encoding, or empty/null for the platform default
      Returns:
      the header line followed by the selected lines, or null if aInputStream is null
      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 from
      aDivider - column divider (used as regular expression)
      aEncoding - character encoding, or empty/null for 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 write
      aFile - file to write to
      Throws:
      IOException - if the file cannot be written
    • readLastLineOfFile

      public static final String readLastLineOfFile(File aFile) throws IOException
      Reads the last line of a text file (platform default encoding).
      Parameters:
      aFile - file to read from (see getInputStream(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 from
      aEncoding - character encoding
      Returns:
      the content
      Throws:
      IOException - if the stream cannot be read or the encoding is not supported
    • stringFromInputStream

      public static final String stringFromInputStream(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
    • 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 from
      aEncoding - 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 from
      aEncoding - 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

      public static final String platformDefaultToUTF8(String aString) throws IOException
      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

      public static final boolean isXMLFileExtension(String aExtension)
      Checks whether a file extension belongs to a (UTF-8 encoded) XML file: xml, aiform, aidocdef or aidoc, ignoring case.
      Parameters:
      aExtension - extension without dot
      Returns:
      true if it is an XML file extension
    • UTF8ToPlatformDefault

      public static final String UTF8ToPlatformDefault(String aString) throws IOException
      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 write
      aOutputStream - 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 write
      aOutputStream - 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 write
      aOutputStream - 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 write
      aOutputStream - stream to write to
      aEncoding - character encoding, or empty/null for 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 write
      aOutputStream - stream to write to
      aEncoding - character encoding, or empty/null for the default (see stringToOutputStreamAndClose(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 .gz are compressed (see getOutputStream(File)).
      Parameters:
      aString - text to write
      aFile - file to write to
      aEncoding - character encoding, or empty/null for the default
      Throws:
      IOException - if writing fails
    • stringToFile

      public static final void stringToFile(String aString, File aFile) throws IOException
      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 .gz are compressed (see getOutputStream(File)).
      Parameters:
      aString - text to write
      aFile - 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 read
      aOutputStream - 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 to
      aInputStream - 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 from
      aOutputStream - stream to write to; flushed at the end
      Throws:
      IOException - if reading or writing fails; both streams are closed in this case
    • copyStream

      public static final void copyStream(Reader aReader, Writer aWriter) throws IOException
      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 from
      aWriter - writer to write to; flushed at the end
      Throws:
      IOException - if reading or writing fails; both are closed in this case
    • createDir

      public static final void createDir(File aDir) throws IOException
      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

      public static final boolean deleteFile(File aFile)
      Deletes a file if it exists.
      Parameters:
      aFile - file to delete
      Returns:
      true if the file was deleted or did not exist
    • getFiles

      public static final List<File> getFiles(File aFile, boolean aShouldIncludeSubdirs)
      Returns all files in a directory, optionally including the files in its subdirectories. Directories themselves are not returned.
      Parameters:
      aFile - directory to search
      aShouldIncludeSubdirs - if true, 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 search
      aRegexpPattern - regular expression the file name (without path) must match; empty for all files
      aShouldIncludeSubdirs - if true, subdirectories are searched recursively
      aIgnoreCase - if true, the pattern is matched ignoring case
      Returns:
      the matching files; empty if aFile is not an existing directory
    • deleteFiles

      public static final void deleteFiles(File aFile) throws IOException
      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

      public static void deleteFiles(File aSourceDir, FileFilter aFileFilter)
      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 deleted
      aFileFilter - filter for the entries to delete, or null for all
    • deleteFiles

      public static final boolean deleteFiles(Collection<File> aFilesCollection)
      Deletes all files of a collection. Stops at the first file that cannot be deleted.
      Parameters:
      aFilesCollection - files to delete
      Returns:
      true if all files were deleted
    • deleteDir

      public static final boolean deleteDir(File dir)
      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:
      true if everything was deleted
    • deleteDir

      public static final boolean deleteDir(File dir, boolean goOnWithError)
      Deletes a directory with all its content. If a file is given, it is deleted.
      Parameters:
      dir - directory or file to delete
      goOnWithError - if true, deletion continues with the remaining entries after an error
      Returns:
      true if the directory itself was deleted
    • isEmpty

      public static final boolean isEmpty(File aDirectory)
      Checks whether a directory contains no files, neither directly nor in any subdirectory.
      Parameters:
      aDirectory - directory to check
      Returns:
      true if the directory tree contains no files; false if aDirectory is a file
    • deleteDirContents

      public static final boolean deleteDirContents(File dir, boolean goOnOnError)
      Deletes the complete content of a directory (files and subdirectories), but not the directory itself.
      Parameters:
      dir - directory to empty
      goOnOnError - if true, deletion continues with the remaining entries after an error
      Returns:
      true if all entries were deleted (also for an empty or missing directory), false if an entry could not be deleted
    • deleteDirContents

      public static final boolean deleteDirContents(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. The directory itself is not deleted.
      Parameters:
      aDir - directory whose files are deleted
      aExtension - extension without dot (ignoring case), or null for all files
      aOlderThanMillis - only files last modified before this time (milliseconds since 1970) are deleted; negative for all
      Returns:
      false if 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 search
      aExtension - extension without dot (ignoring case), or null for all files
      aOlderThanMillis - 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

      public static final List<File> getDirectoriesOnly(File aDir, boolean aRecursive)
      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 search
      aRecursive - if true, the leaf directories of the whole tree are returned; otherwise the direct subdirectories
      Returns:
      the directories found
    • deleteDirContents

      public static final boolean deleteDirContents(File aDir, String aExtension)
      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 deleted
      aExtension - extension without dot, compared ignoring case
      Returns:
      false if a file could not be deleted; otherwise whether the directory exists
    • returnValidFilename

      public static final String returnValidFilename(String aUncheckedFilename)
      Removes characters that are not allowed in file names, including slashes and backslashes. Only pass the file name without path.
      Parameters:
      aUncheckedFilename - file name to clean
      Returns:
      the cleaned file name
      See Also:
    • returnValidPath

      public static final String returnValidPath(String aUncheckedFilename)
      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) and getInvalidFilenameCharacters().

      Parameters:
      aUncheckedFilename - path to clean
      Returns:
      the cleaned path
    • isValidFilename

      public static final boolean isValidFilename(String aFilename)
      Checks whether a file name contains none of the invalid characters listed in getInvalidFilenameCharacters(). Only pass the file name without path.

      If you add or remove characters, also change returnValidPath(String) and getInvalidFilenameCharacters().

      Parameters:
      aFilename - file name to check
      Returns:
      true if the file name is valid
    • getInvalidFilenameCharacters

      public static final String 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) and isValidFilename(String).

      Returns:
      the invalid characters, separated by spaces
    • getFileSizeString

      public static String getFileSizeString(long aByte)
      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

      public static String getHostNameOfLocalSystem() throws UnknownHostException
      Returns:
      the host name of the local system
      Throws:
      UnknownHostException - if the local host name cannot be resolved
    • getIPOfLocalSystem

      public static String getIPOfLocalSystem() throws UnknownHostException
      Returns:
      the IP address of the local system in dotted format
      Throws:
      UnknownHostException - if the local host name cannot be resolved
    • getTemporaryExecutionFilePath

      public static String getTemporaryExecutionFilePath(String aFilePath) throws IOException
      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 check
      aPatternList - patterns (see doesPatternFit(String, String, boolean))
      aIgnoreCase - if true, case is ignored
      Returns:
      true if at least one pattern matches
    • doesPatternFit

      public static boolean doesPatternFit(String aFileName, String aPattern, boolean aIgnoreCase)
      Checks whether a file name matches a pattern. The pattern is a regular expression in which * is additionally replaced by .*, so simple wildcards like *.xml work (note that . still matches any character).
      Parameters:
      aFileName - file name to check
      aPattern - pattern
      aIgnoreCase - if true, case is ignored
      Returns:
      true if the whole file name matches
    • getRelativePath

      public static String getRelativePath(File aFromDir, File aToFileOrDir) throws IOException
      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 from
      aToFileOrDir - 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 directory
      aFileCollection - collection the files are added to
      aIncludeDirectories - if true, 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 directory
      aFileCollection - collection the files are added to
      aExtensionFilter - only files whose name ends with this string are added; empty or null for 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 directory
      aIncludeDirectories - if true, directories are included as well (only if no extension filter is given)
      aExtensionFilter - only files whose name ends with this string are returned; empty or null for all files
      Returns:
      a new collection with the files
    • getFileSize

      public static long getFileSize(File aFile, boolean aRecursive)
      Returns the size of a file. For a directory, the sizes of the files in it are added.
      Parameters:
      aFile - file or directory
      aRecursive - if true, the files in subdirectories are included
      Returns:
      the size in bytes
    • getFilesWithExtension

      public static ArrayList<File> getFilesWithExtension(File aDirectory, String aExtension)
      Returns the files of a directory (not of its subdirectories) with a given extension.
      Parameters:
      aDirectory - directory in which to search
      aExtension - 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 search
      aExtension - extension without dot, compared ignoring case
      aIncludeSubDirs - if true, subdirectories are searched recursively
      Returns:
      the matching files; empty if aDirectory is not a directory
    • getBytesFromFile

      public static byte[] getBytesFromFile(File aFile) throws IOException
      Reads the complete content of a file into a byte array.
      Parameters:
      aFile - file to read (see getInputStream(File) for supported sources)
      Returns:
      the content of the file
      Throws:
      IOException - if the file cannot be read completely
      IllegalArgumentException - if the file length is more than Integer.MAX_VALUE
    • isInDirectory

      public static boolean isInDirectory(File aFile, File aDirectory)
      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 check
      aDirectory - directory
      Returns:
      true if aFile is aDirectory or lies below it
    • createLockFile

      public static boolean createLockFile(File aDirectory)
      Creates a lock file .lock in 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:
      true if the lock was created, false if an existing lock file could not be deleted
    • getFile

      public static File getFile(Collection<File> aFileCollection, String aFileName)
      Finds a file with a given name (without path) in a collection.
      Parameters:
      aFileCollection - files to search
      aFileName - file name to look for (case sensitive)
      Returns:
      the first matching file, or null if there is none
    • toURL

      public static URL toURL(String aURL) throws MalformedURLException
      Creates a URL from an absolute URL string, replacing the deprecated constructor new URL(String). Unlike URI.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 is null, not absolute (no protocol), has an unknown protocol or is no valid URL
    • checkURL

      public static URL checkURL(String aURL)
      Converts a string into a URL. Local paths (starting with a file system root) become file URLs; strings without protocol get ftp://, gopher:// or http:// prepended if they look like a host name. Otherwise the string is taken as file or directory (with index.html/index.htm) or as class path resource. A warning is shown (see FWClientContext.showWarning(String)) for null or invalid URLs.
      Parameters:
      aURL - string to convert
      Returns:
      the URL, or null if it cannot be determined
    • doesFileExist

      public static boolean doesFileExist(String aPath, boolean aSouldAcceptDirectories)
      Checks whether a file exists in the file system or as resource on the class path.
      Parameters:
      aPath - path to check
      aSouldAcceptDirectories - if true, directories count as existing files
      Returns:
      true if 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 (see getInputStream(File) for supported sources)
      aDivider - column divider
      aIncludeHeader - if true, 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 are null. The stream is closed afterwards.
      Parameters:
      aInputStream - stream to read
      aDivider - column divider (see StringHelper.getListFromString(String, String, boolean, boolean))
      aIncludeHeader - if true, 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

      public static Object resizeArray(Object oldArray, int newSize)
      Reallocates an array with a new size, and copies the contents of the old array to the new array.
      Parameters:
      oldArray - the old array, to be reallocated.
      newSize - the new array size.
      Returns:
      A new array with the same contents.
    • 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 write
      aFile - file to write to
      aSeperator - separator between the values
      Throws:
      IOException - if the file cannot be written
      See Also:
    • fillWithZero

      public static <T extends Number> void fillWithZero(T[][] aValuesArray)
      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

      public static void setAuthentication(String aUsername, String aPassword)
      Sets the credentials used for SMB network shares.
      Parameters:
      aUsername - the user name
      aPassword - the password of the user
    • cleanPath

      public static String cleanPath(String aFileName)
      Normalises a path: backslashes are replaced by slashes and dir/../ sequences are resolved.
      Parameters:
      aFileName - path to clean
      Returns:
      the cleaned path
    • hasAuthentication

      public static boolean hasAuthentication()
      Returns:
      true if 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; .gz is appended if missing
      aFilesForPattern - files to combine, in this order
      aHeaderLinesToInclude - 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