Class IOUtil
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intCopies the existing directory and overwrites any files with the same name in the destination directory.static final intCopies the existing directory.static final intIgnores a directory copy command if the destination directory already exists.static final StringSystem.getProperty("file.separator") for conveniencestatic final intstatic final intstatic final longnumber of bytes equal to 2^32static final StringSystem.getProperty("line.separator") for conveniencestatic final intnumber of bytes contained in a gigabyte.static final intnumber of bytes contained in a kilobytestatic final intnumber of bytes contained in a megabyte.static final StringSystem.getProperty("path.separator") for convenience -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic CharBufferarrayToCharBuffer(byte[] array) Convenience method that delegates toarrayToCharBuffer(byte[], String)using UTF-8 encoding by default.static CharBufferarrayToCharBuffer(byte[] array, String encoding) Converts the specified byte array into a CharBuffer using the specified encoding.static voidbeep()Beeps by writing the beep control code to System.outstatic BufferedReaderbufferReader(Reader in) static BufferedInputStreamBuffers and returns the specified InputStream, if it is not already buffered.static BufferedOutputStreambufferStream(OutputStream out) Buffers and returns the specified OutputStream, if it is not already buffered.static BufferedWriterbufferWriter(Writer out) static booleancopyDirectory(File source, File dest) CallscopyFile(File, File, int)with theDIRCOPY_ADD_OR_OVERWRITEflag.static booleancopyDirectory(File source, File dest, int copyflag) Copies the source directory and all it's contents to the specified destination directory.static booleanCopies source file (not directory) to destination.static booleanCopies the source file (not directory) to the specified destination file or directory.static voidcopyStream(InputStream in, OutputStream out) Copies all data from the specific input stream to the specified output stream.static booleandeepDelete(File f) This method recursively removes a specified file or recursively removes a specified directory.static longGets the total size for a directory and all of it's contents.static StringfileSizeToString(long filesize) Converts the specified file size into a human readable description.static StringfileSizeToString(long filesize, int length) CallsfileSizeToString(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 ByteBufferfileToByteBuffer(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 ListfileToLines(File file) Returns the contents of an entire file as a List of individual lines.static ListfileToLines(File file, boolean trim, String comment_chars) Returns the contents of an entire file as a List of individual lines.static ListReturns the contents of an entire file as a List of individual lines.static ListfileToLines(InputStream instream, boolean trim, String comment_chars) Returns the contents of an entire file as a List of individual lines.static ListfileToLines(String filename) Returns the contents of an entire file as a List of individual lines.static StringfileToString(File file) CallsfileToString(String, boolean)with trim being false (that is, files are not trimmed at their trailing end).static StringfileToString(File file, boolean trim) Returns the contents of an entire file as a String.static StringfileToString(String filename) CallsfileToString(String, boolean)with trim being false (that is, files are not trimmed at their trailing end).static StringfileToString(String filename, boolean trim) Returns the contents of an entire file as a String.static InputStreamgetClassResource(Class clazz, String resource_name) Get the InputStream for the specified resource (in the same directory as from where the specified class was loaded).static StringReturns the default encoding used by the current platform.static byte[]Calls inputStreamToByteArray(in, true)static byte[]inputStreamToByteArray(InputStream in, boolean block) Reads the entire InputStream and returns all read data as a byte[].static StringCalls inputStreamToString(in, true)static StringinputStreamToString(InputStream in, boolean block) Reads the entire InputStream and returns all read data as a String, using UTF-8 encoding.static StringinputStreamToString(InputStream in, String encoding) Reads the entire InputStream and returns all read data as a String (using the specified platform encoding).static voidUsage: java IOUtil args where args are: -file full-path-to-file [for fileToString and other tests]static StringpropertiesToString(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 char[]readerToCharArray(Reader reader, int buffer_size) static voidsaveStreamToFile(InputStream in, File f) static final Stringsha1hash(byte[] buf) Returns the SHA-1 hash of the specified byte buffer.static voidAlphabetizes the specified list by the filename.static StringConvenience method that returns the current execution stack trace as a String.static longstringToFileSize(String str) Converts a string file size into a number denoting the equivalent bytes.static StringConvenience method to print the stack trace of an Exception (or Throwable) to a String (using the default platform encoding).static PrintStreamstatic PrintWritertoPrintWriter(Writer out)
-
Field Details
-
FILE_SEP
-
PATH_SEP
-
LINE_SEP
-
FILECOPY_OVERWRITE
- See Also:
-
FILECOPY_NO_OVERWRITE
- See Also:
-
DIRCOPY_NO_OVERWRITE
Ignores a directory copy command if the destination directory already exists.- See Also:
-
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:
-
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:
-
ONE_KB
-
ONE_MB
-
ONE_GB
-
FOUR_GB
-
-
Constructor Details
-
IOUtil
public IOUtil()
-
-
Method Details
-
beep
Beeps by writing the beep control code to System.out -
copyFile
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:
FileNotFoundExceptionIOException- 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 appropriateFILECOPY_OVERWRITEorFILECOPY_NO_OVERWRITEflags. 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.Filedest- the destination file or directory.copyflag- the file copy mode.FILECOPY_OVERWRITE,FILECOPY_NO_OVERWRITE- Throws:
FileNotFoundExceptionIOException
-
copyDirectory
public static boolean copyDirectory(File source, File dest) throws FileNotFoundException, IOException CallscopyFile(File, File, int)with theDIRCOPY_ADD_OR_OVERWRITEflag.- Parameters:
dest- the destination directory.file- the source directory to be copied- Throws:
FileNotFoundExceptionIOException- See Also:
-
copyDirectory
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_OVERWRITEDIRCOPY_DELETE_AND_WRITEandDIRCOPY_ADD_OR_OVERWRITEflags.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.Filedest- the destination file or directory.copyflag- the dir copy mode.DIRCOPY_NO_OVERWRITE,DIRCOPY_ADD_OR_OVERWRITE- Throws:
IOException
-
copyStream
Copies all data from the specific input stream to the specified output stream. Closes both streams after it is finished.- Parameters:
in- the InputStreamout- the OutputStream- Throws:
IOException
-
saveStreamToFile
- Throws:
IOException
-
sortByFileName
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
String.compareTo(String)implementation of String.- Parameters:
list- the list to be sorted
-
deepDelete
This method recursively removes a specified file or recursively removes a specified directory. It is needed (as of JDK 1.4) becauseFile.delete()lacks the ability to delete a directory if the directory is not empty.Internally, this method delegates to
File.delete(), so ifFile.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
-
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
-
toPrintStream
-
toPrintWriter
-
bufferWriter
-
propertiesToString
Convenience method to print the contents of a java.util.Property object to a String (using the default platform encoding). -
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 readtrim- 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
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
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
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
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
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
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
CallsfileToString(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
CallsfileToString(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
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
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
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 theMappedByteBufferdocumentation 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
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 readencoding- 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
- Throws:
IOException
-
readerToCharArray
- Throws:
IOException
-
arrayToCharBuffer
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 convertencoding- thecharsetencoding to use to convert bytes into chars
-
arrayToCharBuffer
Convenience method that delegates toarrayToCharBuffer(byte[], String)using UTF-8 encoding by default. -
inputStreamToByteArray
Reads the entire InputStream and returns all read data as a byte[]. If no data is available, returns null.- Parameters:
in- the InputStream to readblock- 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
Calls inputStreamToByteArray(in, true)- Throws:
IOException
-
inputStreamToString
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 readblock- 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
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 readencoding- theCharsetencoding name to use to convert bytes into chars- Throws:
IOException
-
inputStreamToString
Calls inputStreamToString(in, true)- Throws:
IOException
-
throwableToString
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
Convenience method that returns the current execution stack trace as a String. (using the default platform encoding). -
fileSizeToString
CallsfileSizeToString(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 byteslength- the max number of digits after the decimal point
-
fileSizeToString
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
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
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
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
-