fc.io
Class IOUtil

java.lang.Object
  extended by fc.io.IOUtil

public class IOUtil
extends Object

Misc. IO utilities

Version:
1.1

Field Summary
static int DIRCOPY_ADD_OR_OVERWRITE
          Copies the existing directory and overwrites any files with the same name in the destination directory.
static int DIRCOPY_DELETE_AND_WRITE
          Copies the existing directory.
static int DIRCOPY_NO_OVERWRITE
          Ignores a directory copy command if the destination directory already exists.
static String FILE_SEP
          System.getProperty("file.separator") for convenience
static int FILECOPY_NO_OVERWRITE
           
static int FILECOPY_OVERWRITE
           
static long FOUR_GB
          number of bytes equal to 2^32
static String LINE_SEP
          System.getProperty("line.separator") for convenience
static int ONE_GB
          number of bytes contained in a gigabyte.
static int ONE_KB
          number of bytes contained in a kilobyte
static int ONE_MB
          number of bytes contained in a megabyte.
static String PATH_SEP
          System.getProperty("path.separator") for convenience
 
Constructor Summary
IOUtil()
           
 
Method Summary
static CharBuffer arrayToCharBuffer(byte[] array)
          Convenience method that delegates to arrayToCharBuffer(byte[], String) using UTF-8 encoding by default.
static CharBuffer arrayToCharBuffer(byte[] array, String encoding)
          Converts the specified byte array into a CharBuffer using the specified encoding.
static void beep()
          Beeps by writing the beep control code to System.out
static BufferedReader bufferReader(Reader in)
           
static BufferedInputStream bufferStream(InputStream in)
          Buffers and returns the specified InputStream, if it is not already buffered.
static BufferedOutputStream bufferStream(OutputStream out)
          Buffers and returns the specified OutputStream, if it is not already buffered.
static BufferedWriter bufferWriter(Writer out)
           
static boolean copyDirectory(File source, File dest)
          Calls copyFile(File, File, int) with the DIRCOPY_ADD_OR_OVERWRITE flag.
static boolean copyDirectory(File source, File dest, int copyflag)
          Copies the source directory and all it's contents to the specified destination directory.
static boolean copyFile(File source, File dest)
          Copies source file (not directory) to destination.
static boolean copyFile(File source, File dest, int copyflag)
          Copies the source file (not directory) to the specified destination file or directory.
static void copyStream(InputStream in, OutputStream out)
          Copies all data from the specific input stream to the specified output stream.
static boolean deepDelete(File f)
          This method recursively removes a specified file or recursively removes a specified directory.
static long dirSize(File dir)
          Gets the total size for a directory and all of it's contents.
static String fileSizeToString(long filesize)
          Converts the specified file size into a human readable description.
static String fileSizeToString(long filesize, int length)
          Calls fileSizeToString(long) and truncates the size to fit in the specified number of digits.
static byte[] fileToByteArray(File file)
          Returns the contents of an entire file as a byte[].
static byte[] fileToByteArray(String filename)
          Returns the contents of an entire file as a byte[].
static ByteBuffer fileToByteBuffer(File file)
          Returns the contents of an entire file as a ByteBuffer backed by mapping the file to memory.
static char[] fileToCharArray(File file, String encoding)
          Returns the contents of an entire file as a char[].
static String fileToString(File file)
          Calls fileToString(String, boolean) with trim being false (that is, files are not trimmed at their trailing end).
static String fileToString(File file, boolean trim)
          Returns the contents of an entire file as a String.
static String fileToString(String filename)
          Calls fileToString(String, boolean) with trim being false (that is, files are not trimmed at their trailing end).
static String fileToString(String filename, boolean trim)
          Returns the contents of an entire file as a String.
static String getDefaultEncoding()
          Returns the default encoding used by the current platform.
static byte[] inputStreamToByteArray(InputStream in)
          Calls inputStreamToByteArray(in, true)
static byte[] inputStreamToByteArray(InputStream in, boolean block)
          Reads the entire InputStream and returns all read data as a byte[].
static String inputStreamToString(InputStream in)
          Calls inputStreamToString(in, true)
static String inputStreamToString(InputStream in, boolean block)
          Reads the entire InputStream and returns all read data as a String (using the default platform encoding).
static String inputStreamToString(InputStream in, String encoding)
          Reads the entire InputStream and returns all read data as a String (using the specified platform encoding).
static void main(String[] args)
          Usage: java IOUtil args where args are: -fileToString full-path-to-file [to convert to String (for fileToString() method)]
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).
static char[] readerToCharArray(Reader reader)
           
static String sha1hash(byte[] buf)
          Returns the SHA-1 hash of the specified byte buffer.
static void sortByFileName(List c)
          Alphabetizes the specified list by the filename.
static String stackTrace()
          Convenience method that returns the current execution stack trace as a String.
static long stringToFileSize(String str)
          Converts a string file size into a number denoting the equivalent bytes.
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).
static PrintStream toPrintStream(OutputStream out)
           
static PrintWriter toPrintWriter(Writer out)
           
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

FILE_SEP

public static final String FILE_SEP
System.getProperty("file.separator") for convenience


PATH_SEP

public static final String PATH_SEP
System.getProperty("path.separator") for convenience


LINE_SEP

public static final String LINE_SEP
System.getProperty("line.separator") for convenience


FILECOPY_OVERWRITE

public static final int FILECOPY_OVERWRITE
See Also:
Constant Field Values

FILECOPY_NO_OVERWRITE

public static final int FILECOPY_NO_OVERWRITE
See Also:
Constant Field Values

DIRCOPY_NO_OVERWRITE

public static final int DIRCOPY_NO_OVERWRITE
Ignores a directory copy command if the destination directory already exists.

See Also:
Constant Field Values

DIRCOPY_ADD_OR_OVERWRITE

public static final int DIRCOPY_ADD_OR_OVERWRITE
Copies the existing directory and overwrites any files with the same name in the destination directory. Files/directories that exist in the destination but not in the source directory are left untouched.

See Also:
Constant Field Values

DIRCOPY_DELETE_AND_WRITE

public static final int DIRCOPY_DELETE_AND_WRITE
Copies the existing directory. If the destination directory already exists, the entire target directory is first deleted and then the specified directory is copied to the destination

See Also:
Constant Field Values

ONE_KB

public static final int ONE_KB
number of bytes contained in a kilobyte

See Also:
Constant Field Values

ONE_MB

public static final int ONE_MB
number of bytes contained in a megabyte.

See Also:
Constant Field Values

ONE_GB

public static final int ONE_GB
number of bytes contained in a gigabyte.

See Also:
Constant Field Values

FOUR_GB

public static final long FOUR_GB
number of bytes equal to 2^32

See Also:
Constant Field Values
Constructor Detail

IOUtil

public IOUtil()
Method Detail

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:
file - the source file to be copied, a java.io.File
dest - the destination file or directory.
Throws:
FileNotFoundException
IOException
See Also:
copyFile(File, File, int)

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
Calls copyFile(File, File, int) with the DIRCOPY_ADD_OR_OVERWRITE flag.

Parameters:
file - the source directory to be copied
dest - the destination directory.
Throws:
FileNotFoundException
IOException
See Also:
copyFile(File, File, int)

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

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: 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

public static BufferedInputStream bufferStream(InputStream in)
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

public static BufferedOutputStream bufferStream(OutputStream out)
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.


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:
filename - the file to be read
trim - if true, any trailing whitespace is trimmed from the file's end.
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:
file - the absolute path to the file name to be read
trim - if true, any trailing whitespace is trimmed from the file's end.
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 Buffer.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

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 the default platform 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

public static String inputStreamToString(InputStream in)
                                  throws IOException
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

main

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

Throws:
Exception