Class IOUtil

java.lang.Object
fc.io.IOUtil

public final class IOUtil extends Object
Misc. IO utilities
Version:
1.1
  • Field Details

  • Constructor Details

  • Method Details

    • beep

      public static void beep()
      Beeps by writing the beep control code to System.out
    • copyFile

      public static boolean copyFile(File source, File dest) throws FileNotFoundException, IOException
      Copies source file (not directory) to destination. If the destination already exists, then no copy is made (that is, the destination is not overwritten and this method returns silently (an Exception is not thrown).
      Parameters:
      dest - the destination file or directory.
      file - the source file to be copied, a java.io.File
      Throws:
      FileNotFoundException
      IOException
      See Also:
    • copyFile

      public static boolean copyFile(File source, File dest, int copyflag) throws FileNotFoundException, IOException
      Copies the source file (not directory) to the specified destination file or directory. If a directory is specified as the destination, then the source file is copied into that directory. To specify the action when a file with the same name already exists in the specified directory, use the appropriate FILECOPY_OVERWRITE or FILECOPY_NO_OVERWRITE flags. If a file is specified as the destination, then the source file is copied to that file. If the specified file exists already then specify the appropriate overwrite flag.

      Try to use absolute path names for files and directories. Relative path names can be relative either to user.dir or where the jvm was invoked or some platform/jvm dependent place, so don't rely on relative paths. Copying, moving or working with files is tricky in java. Similar behavior is not defined for all platforms. For example, in WindowsNT/java1.2, aliases cannot be opened/resolved and hence cannot be copied via FileInput/Output streams. This sort of thing is best left to JNI calls native code.

      This method returns true if the directory was copied successfully, false otherwise. (for example, false will be returned when the copy mode is not to overwrite but the target file already exists).

      Parameters:
      source - the source file (not directory) to be copied, a java.io.File
      dest - the destination file or directory.
      copyflag - the file copy mode. FILECOPY_OVERWRITE, FILECOPY_NO_OVERWRITE
      Throws:
      FileNotFoundException
      IOException
    • copyDirectory

      public static boolean copyDirectory(File source, File dest) throws FileNotFoundException, IOException
      Parameters:
      dest - the destination directory.
      file - the source directory to be copied
      Throws:
      FileNotFoundException
      IOException
      See Also:
    • copyDirectory

      public static boolean copyDirectory(File source, File dest, int copyflag) throws IOException
      Copies the source directory and all it's contents to the specified destination directory. A directory must be specified both for the source and the destination.

      To handle cases where the destination directory already exists use the appropriate DIRCOPY_NO_OVERWRITE DIRCOPY_DELETE_AND_WRITE and DIRCOPY_ADD_OR_OVERWRITE flags.

      Try to use absolute path names for files and directories. Relative path names can be relative either to user.dir or where the jvm was invoked or some platform/jvm dependent place, so don't rely on relative paths. Copying, moving or working with files is tricky in java. Similar behavior is not defined for all platforms. For example, in WindowsNT/java1.2, aliases cannot be opened/resolved and hence cannot be copied via FileInput/Output streams. This sort of thing is best left to JNI calls to POSIX or to platform specific code.

      This method returns true if the directory was copied successfully, false otherwise. (for example, false will be returned when the copy mode is not to overwrite but the target directory already exists).

      Parameters:
      source - the source directory (not file) to be copied, a java.io.File
      dest - the destination file or directory.
      copyflag - the dir copy mode. DIRCOPY_NO_OVERWRITE, DIRCOPY_ADD_OR_OVERWRITE
      Throws:
      IOException
    • copyStream

      public static void copyStream(InputStream in, OutputStream out) throws IOException
      Copies all data from the specific input stream to the specified output stream. Closes both streams after it is finished.
      Parameters:
      in - the InputStream
      out - the OutputStream
      Throws:
      IOException
    • saveStreamToFile

      public static void saveStreamToFile(InputStream in, File f) throws IOException
      Throws:
      IOException
    • sortByFileName

      public static void sortByFileName(List c)
      Alphabetizes the specified list by the filename. Only the filename is considered and not the path name (if any). The collection should contain one of:
      • java.io.File
      • String[]
      • Object
      Any/all of these can be contained in the specified list at the same time. If a String[] is found, the 0th element (i.e., (String[] foo)[0]) is used for comparison purposes. The list is sorted by the default String.compareTo(String) implementation of String.
      Parameters:
      list - the list to be sorted
    • deepDelete

      public static boolean deepDelete(File f)
      This method recursively removes a specified file or recursively removes a specified directory. It is needed (as of JDK 1.4) because File.delete() lacks the ability to delete a directory if the directory is not empty.

      Internally, this method delegates to File.delete(), so if File.delete() follows sym links, then so will this method. Be careful !

      Parameters:
      file - the file or directory to be removed
      Returns:
      true on success, false otherwise. Also returns false if the specified file or directory does not exist.
    • dirSize

      public static long dirSize(File dir)
      Gets the total size for a directory and all of it's contents. If the specified argument is a regular file, returns the size of that file itself.
      Parameters:
      dir - the target dir
      Returns:
      the directory or file size in bytes
    • bufferStream

      Buffers and returns the specified InputStream, if it is not already buffered. Does not buffer an already buffered stream but returns it as is.
      Parameters:
      in - the input stream to be buffered
      Returns:
      the buffered stream
    • bufferStream

      Buffers and returns the specified OutputStream, if it is not already buffered. Does not buffer an already buffered stream but returns it as is.
      Parameters:
      out - the output stream to be buffered
      Returns:
      the buffered stream
    • bufferReader

      public static BufferedReader bufferReader(Reader in)
    • toPrintStream

      public static PrintStream toPrintStream(OutputStream out)
    • toPrintWriter

      public static PrintWriter toPrintWriter(Writer out)
    • bufferWriter

      public static BufferedWriter bufferWriter(Writer out)
    • propertiesToString

      public static String propertiesToString(Properties props)
      Convenience method to print the contents of a java.util.Property object to a String (using the default platform encoding).
    • getDefaultEncoding

      public static String getDefaultEncoding()
      Returns the default encoding used by the current platform. Returns null is the default encoding cannot be determined.
    • fileToLines

      public static List fileToLines(InputStream instream, boolean trim, String comment_chars) throws IOException
      Returns the contents of an entire file as a List of individual lines. If the specified file does not exist or have no content return an empty List. Uses UTF-8 encoding to read the file.
      Parameters:
      instream - the stream to be read
      trim - if true, any leading or trailing blank lines are trimmed are ignored.
      comment_chars - Regex of comment chars. Any lines that start with this (or have leading spaces and then start with this) are ignored. (example: # or #|//)
      Throws:
      IOException
    • fileToLines

      public static List fileToLines(File file, boolean trim, String comment_chars) throws IOException
      Returns the contents of an entire file as a List of individual lines. If the specified file does not exist or have no content return an empty List.
      Parameters:
      trim - if true, any leading or trailing blank lines are trimmed are ignored.
      comment_chars - Regex of comment chars. Any lines that start with this (or have leading spaces and then start with this) are ignored. (example: # or #|//)
      File - the file to be read ("UTF-8" encoding is used)
      Throws:
      IOException
    • fileToLines

      public static List fileToLines(File file) throws IOException
      Returns the contents of an entire file as a List of individual lines. Empty lines are trimmed and lines beginning with the following characters are ignored: # and //
      Parameters:
      file - the file to be read ("UTF-8" encoding is used)
      Throws:
      IOException
    • fileToLines

      public static List fileToLines(String filename) throws IOException
      Returns the contents of an entire file as a List of individual lines. Empty lines are trimmed and lines beginning with the following characters are ignored: # and //
      Parameters:
      filename - the file to be read ("UTF-8" encoding is used)
      Throws:
      IOException
    • fileToLines

      public static List fileToLines(InputStream in) throws IOException
      Returns the contents of an entire file as a List of individual lines. Empty lines are trimmed and lines beginning with the following characters are ignored: # and //
      Parameters:
      in - the input stream to be read
      Throws:
      IOException
    • fileToString

      public static String fileToString(File file, boolean trim) throws IOException
      Returns the contents of an entire file as a String. If the specified file does not exist returns null. Files that exist but have no content return an empty String.

      Note 1: Due to jdk1.4 brain damage, this method is limited to files less than 2^32 bytes. If the specified file is greater than 2^32 bytes, an IOException will be thrown.
      Note 2: The files is converted into a String using an encoding that is determined programmatically (from the filesystem). This may not be totally reliable but there is no way around this because JDK 1.4 provides no way to easily get the default platform encoding. Uses the ISO_8859_1 encoding as a fallback measure, if the default encoding cannot be determined.

      Parameters:
      trim - if true, any trailing whitespace is trimmed from the file's end.
      filename - the file to be read
      Throws:
      IOException
    • fileToString

      public static String fileToString(String filename, boolean trim) throws IOException
      Returns the contents of an entire file as a String. If the specified file does not exist returns null. Files that exist but have no content return an empty String.

      Note 1: Due to jdk1.4 brain damage, this method is limited to files less than 2^32 bytes. If the specified file is greater than 2^32 bytes, an IOException will be thrown.
      Note 2: The files is converted into a String using an encoding that is determined programmatically (from the filesystem). This may not be totally reliable but there is no way around this because JDK 1.4 provides no way to easily get the default platform encoding. Uses the ISO_8859_1 encoding as a fallback measure, if the default encoding cannot be determined.

      Parameters:
      trim - if true, any trailing whitespace is trimmed from the file's end.
      file - the absolute path to the file name to be read
      Throws:
      IOException
    • fileToString

      public static String fileToString(String filename) throws IOException
      Calls fileToString(String, boolean) with trim being false (that is, files are not trimmed at their trailing end).
      Parameters:
      filename - the absolute path to the file name to be read
      Throws:
      IOException
    • fileToString

      public static String fileToString(File file) throws IOException
      Calls fileToString(String, boolean) with trim being false (that is, files are not trimmed at their trailing end).
      Parameters:
      file - the file to be read
      Throws:
      IOException
    • fileToByteArray

      public static byte[] fileToByteArray(String filename) throws IOException
      Returns the contents of an entire file as a byte[]. If the specified file does not exist returns null.

      Note 1: Since java arrays cannot be greater than 2^32 elements, this method is limited to files less than or equal to 2^32 bytes. If the specified file is greater than 2^32 bytes, an IOException will be thrown.

      Parameters:
      filename - the absolute path to the file name to be read
      Returns:
      ByteBuffer contains the bytes for that file
      Throws:
      IOException
    • fileToByteArray

      public static byte[] fileToByteArray(File file) throws IOException
      Returns the contents of an entire file as a byte[]. If the specified file does not exist returns null.

      Note 1: Since java arrays cannot be greater than 2^32 elements, this method is limited to files less than or equal to 2^32 bytes. If the specified file is greater than 2^32 bytes, an IOException will be thrown.

      Parameters:
      file - the file to be read
      Returns:
      byte[] contains the bytes for that file
      Throws:
      IOException
    • fileToByteBuffer

      public static ByteBuffer fileToByteBuffer(File file) throws IOException
      Returns the contents of an entire file as a ByteBuffer backed by mapping the file to memory. If the specified file does not exist returns null. Mapped files do not have have a accesible backing array and the ByteBuffer.hasArray() will be false. See the MappedByteBuffer documentation about concurrent modification or deletion of files that are mapped into memory.

      The ByteBuffer returned by this method will have ByteBuffer.rewind() called on it before it is returned.

      Note 1: This method is limited to files less than 2^32 bytes, since ByteBuffers cannot be greater than this size. If the specified file is greater than 2^32 bytes, an IOException will be thrown.

      Parameters:
      file - the file to be read
      Returns:
      ByteBuffer contains the bytes for that file
      Throws:
      IOException
    • fileToCharArray

      public static char[] fileToCharArray(File file, String encoding) throws IOException
      Returns the contents of an entire file as a char[]. If the specified file does not exist returns null.

      Note 1: Since java arrays cannot be greater than 2^32 elements, this method is limited to files less than or equal to 2^32 bytes. If the specified file is greater than 2^32 bytes, an IOException will be thrown.

      Parameters:
      file - the file to be read
      encoding - the name of the character encoding to use. Specify null to use UTF-8 encoding.
      Returns:
      char[] contains the chars for that file
      Throws:
      IOException
    • readerToCharArray

      public static char[] readerToCharArray(Reader reader) throws IOException
      Throws:
      IOException
    • readerToCharArray

      public static char[] readerToCharArray(Reader reader, int buffer_size) throws IOException
      Throws:
      IOException
    • arrayToCharBuffer

      public static CharBuffer arrayToCharBuffer(byte[] array, String encoding)
      Converts the specified byte array into a CharBuffer using the specified encoding. The returned CharBuffer can be directly used in statements such as System.out.println to print it's contents,

      This method returns null if the specified array is null or if the specified encoding is null.

      Parameters:
      array - the array to convert
      encoding - the charset encoding to use to convert bytes into chars
    • arrayToCharBuffer

      public static CharBuffer arrayToCharBuffer(byte[] array)
      Convenience method that delegates to arrayToCharBuffer(byte[], String) using UTF-8 encoding by default.
    • inputStreamToByteArray

      public static byte[] inputStreamToByteArray(InputStream in, boolean block) throws IOException
      Reads the entire InputStream and returns all read data as a byte[]. If no data is available, returns null.
      Parameters:
      in - the InputStream to read
      block - if true, this method will block until all available data from the specified input stream has been read. If false, this method will read and return as much data as currently is available is read without blocking. The available amount is that returned by the available() method of the specified input stream.
      Throws:
      NegativeArraySizeException - if the specified input stream returns a negative number for available()
      IOException
    • inputStreamToByteArray

      public static byte[] inputStreamToByteArray(InputStream in) throws IOException
      Calls inputStreamToByteArray(in, true)
      Throws:
      IOException
    • inputStreamToString

      public static String inputStreamToString(InputStream in, boolean block) throws IOException
      Reads the entire InputStream and returns all read data as a String, using UTF-8 encoding. If no data is available, returns null. The specified input stream is not closed.
      Parameters:
      in - the InputStream to read
      block - if true, this method will block until all available data from the specified input stream has been read. If false, this method will read and return as much data as currently is available is read without blocking. The available amount is that returned by the specified input stream.
      Throws:
      NegativeArraySizeException - if the specified input stream returns a negative number for available()
      IOException
    • inputStreamToString

      public static String inputStreamToString(InputStream in, String encoding) throws IOException
      Reads the entire InputStream and returns all read data as a String (using the specified platform encoding). If no data is available, returns null. The specified input stream is not closed.

      This method will block until all available data from the specified input stream has been read.

      Parameters:
      in - the input stream to read
      encoding - the Charset encoding name to use to convert bytes into chars
      Throws:
      IOException
    • inputStreamToString

      Calls inputStreamToString(in, true)
      Throws:
      IOException
    • throwableToString

      public static String throwableToString(Throwable e)
      Convenience method to print the stack trace of an Exception (or Throwable) to a String (using the default platform encoding). (The getMessage() method of a Throwable does not print the entire stack trace).
    • stackTrace

      public static String stackTrace()
      Convenience method that returns the current execution stack trace as a String. (using the default platform encoding).
    • fileSizeToString

      public static String fileSizeToString(long filesize, int length)
      Calls fileSizeToString(long) and truncates the size to fit in the specified number of digits. For example, a file size of 4.455 KB and a length of 2 will return 4.45 KB
      Parameters:
      filesize - the size of the file in bytes
      length - the max number of digits after the decimal point
    • fileSizeToString

      public static String fileSizeToString(long filesize)
      Converts the specified file size into a human readable description. Similar to the "--human-readable" flag found in various GNU programs.
      Parameters:
      filesize - the size of the file in bytes
    • stringToFileSize

      public static long stringToFileSize(String str)
      Converts a string file size into a number denoting the equivalent bytes. For example:
      34K, 34KB --> 34 bytes
      34M, 34megabytes --> 34 * 1024 bytes
      
      Allows numbers to end with k..., m..., g...., b.... or no suffix at all. Suffixes are case insensitive.
    • sha1hash

      public static final String sha1hash(byte[] buf) throws NoSuchAlgorithmException
      Returns the SHA-1 hash of the specified byte buffer.

      This method is not thread safe (as far as I can tell, since it uses MessageDigest.getInstance, but if that is thread safe, then this method is thread safe). The invoker should invoke it in a thread safe way.

      Throws:
      NoSuchAlgorithmException
    • getClassResource

      public static InputStream getClassResource(Class clazz, String resource_name) throws IOException
      Get the InputStream for the specified resource (in the same directory as from where the specified class was loaded). Returns null if not found.
      Throws:
      IOException
    • main

      public static void main(String[] args) throws Exception
      Usage: java IOUtil args where args are: -file full-path-to-file [for fileToString and other tests]
      Throws:
      Exception