Class IOUtils


  • public class IOUtils
    extends java.lang.Object
    Contains utilities for reading/writing streams.
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static interface  IOUtils.OutputStreamConsumer
      Used for copying an OutputStream into an InputStream.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String DEFAULT_ENCODING
      The default encoding value (UTF-8).
      static java.lang.String EXE_SUFFIX  
      static java.lang.String FILE_SEP  
      static java.lang.String i386
      Deprecated.
      Use I386 instead.
      static java.lang.String I386
      32 bit OS architecture identifier.
      static java.lang.String LINUX
      The 'Linux' OS family identifier.
      static java.lang.String MAC
      The 'Mac' OS family identifier.
      static java.lang.String SOLARIS
      The 'Solaris' OS family identifier.
      static java.lang.String WINDOWS
      The 'Windows' OS family identifier.
      static java.lang.String x32
      Deprecated.
      Use X32 instead.
      static java.lang.String X32
      32 bit OS architecture identifier.
      static java.lang.String x64
      Deprecated.
      Use X64 instead.
      static java.lang.String X64
      64 bit OS architecture identifier.
      static java.lang.String X86_64
      x86/64 bit OS architecture identifier (mac).
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected IOUtils()
      The default constructor (hidden).
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static boolean checkIfPortInUse​(int port)
      Checks to see if a specified port is in use on the local host.
      static java.lang.Exception close​(java.io.Closeable closeable)
      Safely close any Closeable (Input/OutputStreams, Readers, Writers), ignoring Null streams..
      static java.lang.Exception close​(java.io.Closeable closeable, StatusListener statusListener, java.lang.String streamId)
      Safely close any Closeable (Input/OutputStreams, Readers, Writers), ignoring Null streams and logging a message if failure occurs.
      static void copyStream​(java.io.InputStream in, java.io.OutputStream out)
      Copies the contents from an OutputStream into an InputStream.
      static long copyStream​(java.io.InputStream in, java.io.OutputStream out, boolean closeStreams)
      Copies the contents from an OutputStream into an InputStream.
      static java.lang.String findIpAddress​(java.lang.String startsWith)
      Returns the 1st IP address that starts with the given string.
      static java.lang.String fixPathSeparators​(java.lang.String path)
      Make path separators consistent and correct for the local platform.
      static java.lang.String getBinaryExtension()
      Get the binary filename extension for the current platform
      static byte[] getBytes​(java.lang.String s)
      Gets bytes from a String in the proper encoding.
      static java.lang.Long getChecksumFromString​(java.lang.String contents)
      Return the CRC32 checksum for the contents of this string.
      static java.lang.String getIpAddress()  
      static java.lang.String getIpAddress​(java.lang.String host)  
      static java.lang.String getOSArchitecture()
      Gets a nice clean OS cpu architecture name using system properties
      static java.lang.String getOSFamily()
      Gets a nice clean OS name using system properties.
      static int getPID()
      Gets the ProcessID of the JVM from java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
      static java.lang.String getString​(byte[] bytes)
      Gets String from a byte array in proper encoding.
      static java.io.OutputStream getZipOutputStream​(java.util.zip.ZipOutputStream zip, java.lang.String dir, java.lang.String path)
      Get output stream for a zip file.
      static java.io.Writer getZipWriter​(java.util.zip.ZipOutputStream zip, java.lang.String dir, java.lang.String path)
      Get a writer object for writing a file within a zip file
      static void initIpAddress()
      Get the IP address of this node as a String.
      static boolean isLocalHost​(java.lang.String host)
      Note, this method will not return true if host is the real hostname of this system.
      static boolean isPortInUse​(int port, int numRetries)
      Calls isPortInUse(int, int, int) with a retry wait time of 0
      static boolean isPortInUse​(int port, int numRetries, int retryWaitTimeInMilliseconds)
      Checks to see if a port is in use with a given number of loops (numRetries) waiting retryWaitTimeInMilliseconds for each loop.
      static boolean isSameHost​(java.lang.String otherHost)
      Determines is the local host is the same as the otherHost specified.
      static java.lang.String localizedHost​(java.lang.String host)  
      static java.io.Reader openReader​(java.io.File file, java.lang.String encoding)
      Open a reader for a file with a specified encoding.
      static java.io.Reader openReader​(java.net.URI uri, java.lang.String encoding)
      Open a reader for a file with a specified encoding.
      static int randomPort()
      Taken from org.apache.curator.test.InstanceSpec
      static byte[] readAsBytes​(java.io.InputStream is)
      Reads the contents of an InputStream.
      static byte[] readAsBytes​(java.io.InputStream input, int limit)
      Reads up to limit bytes from input.
      static java.lang.String readAsText​(java.io.InputStream in)
      Reads InputStream using the default encoding.
      static java.lang.String readAsText​(java.io.InputStream in, java.lang.String encoding)
      Reads InputStream using the default encoding.
      static java.lang.String readAsText​(java.io.InputStream in, java.nio.charset.Charset charset)
      Reads InputStream using the default encoding.
      static java.lang.String readAsText​(java.io.Reader r)
      Gets the contents of a reader as text.
      static java.lang.String readAsTextSafely​(java.io.InputStream in)
      Reads InputStream using the default encoding, trapping IOException and returning null.
      static void registerURLProtocolHandler​(java.lang.Class<? extends java.net.URLStreamHandler> clazz)
      Register a protocol handler for a specific class.
      static java.io.InputStream toInputStream​(IOUtils.OutputStreamConsumer ss)
      Creates an InputStream which reads data written by the IOUtils.OutputStreamConsumer.
      static java.io.InputStream toInputStream​(IOUtils.OutputStreamConsumer ss, int pipeSize)
      Creates an InputStream which reads data written by the IOUtils.OutputStreamConsumer.
      static java.io.IOException toIOException​(AttivioException ex)
      If the parameter was caused by an IOException, the cause is returned, otherwise a new IOException with the parameter is constructed and returned.
      static java.net.URI toUri​(java.lang.String file)
      Returns a URI representing the file.
      static void write​(java.lang.String s, java.io.OutputStream out)
      Writes out a String.
      static void zipDir​(java.util.zip.ZipOutputStream zip, java.lang.String path, java.io.File dir, java.io.FileFilter ff)
      Take the contents of the directory passed in and add it to the ZIP output stream at the location pointed to by path.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • MAC

        public static final java.lang.String MAC
        The 'Mac' OS family identifier.
        See Also:
        Constant Field Values
      • LINUX

        public static final java.lang.String LINUX
        The 'Linux' OS family identifier.
        See Also:
        Constant Field Values
      • WINDOWS

        public static final java.lang.String WINDOWS
        The 'Windows' OS family identifier.
        See Also:
        Constant Field Values
      • SOLARIS

        public static final java.lang.String SOLARIS
        The 'Solaris' OS family identifier.
        See Also:
        Constant Field Values
      • X64

        public static final java.lang.String X64
        64 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • X86_64

        public static final java.lang.String X86_64
        x86/64 bit OS architecture identifier (mac).
        See Also:
        Constant Field Values
      • X32

        public static final java.lang.String X32
        32 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • I386

        public static final java.lang.String I386
        32 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • x64

        @Deprecated
        public static final java.lang.String x64
        Deprecated.
        Use X64 instead.
        64 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • x32

        @Deprecated
        public static final java.lang.String x32
        Deprecated.
        Use X32 instead.
        32 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • i386

        @Deprecated
        public static final java.lang.String i386
        Deprecated.
        Use I386 instead.
        32 bit OS architecture identifier.
        See Also:
        Constant Field Values
      • DEFAULT_ENCODING

        public static final java.lang.String DEFAULT_ENCODING
        The default encoding value (UTF-8).
        See Also:
        Constant Field Values
      • EXE_SUFFIX

        public static final java.lang.String EXE_SUFFIX
      • FILE_SEP

        public static final java.lang.String FILE_SEP
    • Constructor Detail

      • IOUtils

        protected IOUtils()
        The default constructor (hidden).
    • Method Detail

      • readAsText

        public static java.lang.String readAsText​(java.io.Reader r)
                                           throws java.io.IOException
        Gets the contents of a reader as text. WARNING: Does not close stream
        Parameters:
        r - the reader to read
        Returns:
        String from Reader
        Throws:
        java.io.IOException - if an error occurs reading
      • readAsText

        public static java.lang.String readAsText​(java.io.InputStream in,
                                                  java.lang.String encoding)
                                           throws java.io.IOException
        Reads InputStream using the default encoding. WARNING: Does not close stream
        Parameters:
        in - stream to read
        encoding - encoding to use
        Returns:
        String from InputStream
        Throws:
        java.io.IOException - if an error occurs
      • readAsText

        public static java.lang.String readAsText​(java.io.InputStream in,
                                                  java.nio.charset.Charset charset)
                                           throws java.io.IOException
        Reads InputStream using the default encoding. WARNING: Does not close stream
        Parameters:
        in - stream to read
        charset - encoding to use
        Returns:
        String from InputStream
        Throws:
        java.io.IOException - if an error occurs
      • readAsText

        public static java.lang.String readAsText​(java.io.InputStream in)
                                           throws java.io.IOException
        Reads InputStream using the default encoding. WARNING: Does not close stream
        Parameters:
        in - stream to read in default encoding
        Returns:
        String from InputStream
        Throws:
        java.io.IOException - if an error occurs
      • readAsTextSafely

        public static java.lang.String readAsTextSafely​(java.io.InputStream in)
        Reads InputStream using the default encoding, trapping IOException and returning null. WARNING: Does not close stream
        Parameters:
        in -
        Returns:
        the stream as a string or null if error was encountered reading the stream.
      • readAsBytes

        public static byte[] readAsBytes​(java.io.InputStream is)
                                  throws java.io.IOException
        Reads the contents of an InputStream. WARNING: Does not close stream
        Parameters:
        is - stream to read
        Returns:
        byte array from InputStream
        Throws:
        java.io.IOException - if an error occurs
      • readAsBytes

        public static byte[] readAsBytes​(java.io.InputStream input,
                                         int limit)
                                  throws java.io.IOException
        Reads up to limit bytes from input.

        WARNING: does not close stream.

        Throws:
        java.io.IOException
      • copyStream

        public static void copyStream​(java.io.InputStream in,
                                      java.io.OutputStream out)
                               throws java.io.IOException
        Copies the contents from an OutputStream into an InputStream. Both streams will be closed after the copy operation completes.
        Parameters:
        in - input stream
        out - output stream
        Throws:
        java.io.IOException - if error
        See Also:
        Java I/O Performance
      • copyStream

        public static long copyStream​(java.io.InputStream in,
                                      java.io.OutputStream out,
                                      boolean closeStreams)
                               throws java.io.IOException
        Copies the contents from an OutputStream into an InputStream.
        Parameters:
        in - input stream
        out - output stream
        closeStreams - if true, both streams will be closed after the copy operation completes successfully
        Throws:
        java.io.IOException - if error
        See Also:
        Java I/O Performance
      • getBytes

        public static byte[] getBytes​(java.lang.String s)
        Gets bytes from a String in the proper encoding.
        Parameters:
        s - string to get bytes of
        Returns:
        byte array encoded in UTF-8, if string is null return an empty byte array
      • getString

        public static java.lang.String getString​(byte[] bytes)
        Gets String from a byte array in proper encoding.
        Parameters:
        bytes - byte array to get String from. if bytes is null, returns null
      • getZipWriter

        public static java.io.Writer getZipWriter​(java.util.zip.ZipOutputStream zip,
                                                  java.lang.String dir,
                                                  java.lang.String path)
                                           throws java.io.IOException
        Get a writer object for writing a file within a zip file
        Parameters:
        zip - output stream for the zip file
        dir - directory in the zip file to house file
        path - the path of the file within the zip file
        Returns:
        writer
        Throws:
        java.io.IOException
      • zipDir

        public static void zipDir​(java.util.zip.ZipOutputStream zip,
                                  java.lang.String path,
                                  java.io.File dir,
                                  java.io.FileFilter ff)
                           throws java.io.IOException
        Take the contents of the directory passed in and add it to the ZIP output stream at the location pointed to by path.
        Parameters:
        zip - the ZipOutputStream to add to
        path - the location within the output stream where the contents of the directory should go, or null to put them at the root of the ZIP
        dir - the directory on the local file system of the directory whose contents you want to zip up
        ff - an optional filter to use when looking at the contents of the directory (pass null to include all files)
        Throws:
        java.io.IOException
      • getZipOutputStream

        public static java.io.OutputStream getZipOutputStream​(java.util.zip.ZipOutputStream zip,
                                                              java.lang.String dir,
                                                              java.lang.String path)
                                                       throws java.io.IOException
        Get output stream for a zip file.
        Parameters:
        zip - the output stream
        dir - the directory in the zip file to house file
        path - the path of the file within the zip file
        Returns:
        output stream for the zip file
        Throws:
        java.io.IOException
      • write

        public static void write​(java.lang.String s,
                                 java.io.OutputStream out)
                          throws java.io.IOException
        Writes out a String.
        Parameters:
        s - String to write
        out - Stream to write to in default encoding
        Throws:
        java.io.IOException - if an error occors while writing
      • getPID

        public static int getPID()
        Gets the ProcessID of the JVM from java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
        Returns:
        the process ID of the JVM
      • initIpAddress

        public static void initIpAddress()
        Get the IP address of this node as a String.

        NOTE: in the event that the default local host address is a loopback address, all non-local network interfaces will be searched for the first ipv4 address. This may still result in an address that is not externally available on the network. To avoid this, you must configure your host to use a static ip address.

      • getIpAddress

        public static java.lang.String getIpAddress()
      • findIpAddress

        public static java.lang.String findIpAddress​(java.lang.String startsWith)
                                              throws java.net.UnknownHostException,
                                                     java.net.SocketException
        Returns the 1st IP address that starts with the given string.
        Parameters:
        startsWith -
        Returns:
        Throws:
        java.net.UnknownHostException
        java.net.SocketException
      • isLocalHost

        public static boolean isLocalHost​(java.lang.String host)
        Note, this method will not return true if host is the real hostname of this system.
        Parameters:
        host -
        Returns:
        true if host is null or one of 127.0.0.1, ::1, or localhost
      • localizedHost

        public static java.lang.String localizedHost​(java.lang.String host)
        Parameters:
        host -
        Returns:
        localhost if isLocalHost(String) is true, otherwise returns host.
      • isSameHost

        public static boolean isSameHost​(java.lang.String otherHost)
                                  throws AttivioException
        Determines is the local host is the same as the otherHost specified. Checks to see if any of the IP addresses of the otherHost match any of the IPs of any of this machine's interfaces.
        Parameters:
        otherHost - the host to compare to. if null, the localhost is assumed, thus resulting in a true result.
        Throws:
        AttivioException
      • getIpAddress

        public static java.lang.String getIpAddress​(java.lang.String host)
        Parameters:
        host -
        Returns:
        the IP address of host as a String or null if it could not be found.
      • openReader

        public static java.io.Reader openReader​(java.io.File file,
                                                java.lang.String encoding)
                                         throws java.io.IOException
        Open a reader for a file with a specified encoding.
        Throws:
        java.io.IOException
      • openReader

        public static java.io.Reader openReader​(java.net.URI uri,
                                                java.lang.String encoding)
                                         throws java.io.IOException
        Open a reader for a file with a specified encoding.
        Throws:
        java.io.IOException
      • getOSFamily

        public static java.lang.String getOSFamily()
        Gets a nice clean OS name using system properties.
        Returns:
        the OS name
        See Also:
        MAC, LINUX, WINDOWS, SOLARIS
      • getOSArchitecture

        public static java.lang.String getOSArchitecture()
        Gets a nice clean OS cpu architecture name using system properties
        Returns:
        the CPU Architecture name, either 32 or 64
      • getBinaryExtension

        public static java.lang.String getBinaryExtension()
        Get the binary filename extension for the current platform
        Returns:
        the binary extension (ie .exe for windows)
      • isPortInUse

        public static boolean isPortInUse​(int port,
                                          int numRetries)
        Calls isPortInUse(int, int, int) with a retry wait time of 0
        Parameters:
        port - socket port number
        numRetries - number of attempts to use that socket
        Returns:
        true if port is in use, false otherwise
      • isPortInUse

        public static boolean isPortInUse​(int port,
                                          int numRetries,
                                          int retryWaitTimeInMilliseconds)
        Checks to see if a port is in use with a given number of loops (numRetries) waiting retryWaitTimeInMilliseconds for each loop.
        Parameters:
        port - socket port number
        numRetries - number of attempts to use that socket
        retryWaitTimeInMilliseconds - time in milliseconds to sleep between retries
        Returns:
        true if port is in use, false otherwise
      • fixPathSeparators

        public static java.lang.String fixPathSeparators​(java.lang.String path)
        Make path separators consistent and correct for the local platform.
      • toInputStream

        public static java.io.InputStream toInputStream​(IOUtils.OutputStreamConsumer ss)
                                                 throws java.io.IOException
        Creates an InputStream which reads data written by the IOUtils.OutputStreamConsumer. An OutputStreamConsumer is an interface which provides a single write method that takes an OutputStream.

        Sample use

          class1.read(IOUtils.toInputStream(new OutputStreamConsumer() public void write(OutputStream os) throws IOException
         class2.write(os);
          ));
         }
        Parameters:
        ss - the output stream consumer to write to.
        Returns:
        an InputStream which reads data written by the OutputStreamConsumer.
        Throws:
        java.io.IOException
      • toInputStream

        public static java.io.InputStream toInputStream​(IOUtils.OutputStreamConsumer ss,
                                                        int pipeSize)
                                                 throws java.io.IOException
        Creates an InputStream which reads data written by the IOUtils.OutputStreamConsumer. An OutputStreamConsumer is an interface which provides a single write method that takes an OutputStream.

        Sample use

          class1.read(IOUtils.toInputStream(new OutputStreamConsumer() public void write(OutputStream os) throws IOException
         class2.write(os);
          ));
         }
        Parameters:
        ss - the output stream consumer to write to.
        pipeSize - the size of the buffer between the output and input streams.
        Returns:
        an InputStream which reads data written by the OutputStreamConsumer.
        Throws:
        java.io.IOException
      • toIOException

        public static final java.io.IOException toIOException​(AttivioException ex)
        If the parameter was caused by an IOException, the cause is returned, otherwise a new IOException with the parameter is constructed and returned. This is particularly useful when implementing close() methods which must throw IOExceptions.
        Parameters:
        ex -
        Returns:
        the IOException
      • close

        public static final java.lang.Exception close​(java.io.Closeable closeable)
        Safely close any Closeable (Input/OutputStreams, Readers, Writers), ignoring Null streams..
      • close

        public static final java.lang.Exception close​(java.io.Closeable closeable,
                                                      StatusListener statusListener,
                                                      java.lang.String streamId)
        Safely close any Closeable (Input/OutputStreams, Readers, Writers), ignoring Null streams and logging a message if failure occurs.
      • checkIfPortInUse

        public static boolean checkIfPortInUse​(int port)
        Checks to see if a specified port is in use on the local host.
        Returns:
        true if the port is in use or there was some other exception testing the port, false if port is not in use.
      • randomPort

        public static int randomPort()
        Taken from org.apache.curator.test.InstanceSpec
        Returns:
        a random unused port
      • toUri

        public static java.net.URI toUri​(java.lang.String file)
        Returns a URI representing the file. If file is already a URI, it is returned as a URI
        Parameters:
        file -
        Returns:
        a corresponding URI
      • registerURLProtocolHandler

        public static void registerURLProtocolHandler​(java.lang.Class<? extends java.net.URLStreamHandler> clazz)
        Register a protocol handler for a specific class.
      • getChecksumFromString

        public static java.lang.Long getChecksumFromString​(java.lang.String contents)
                                                    throws java.io.IOException
        Return the CRC32 checksum for the contents of this string.
        Parameters:
        contents -
        Returns:
        checksum
        Throws:
        java.io.IOException