Class StreamHelper

java.lang.Object
com.helger.base.io.stream.StreamHelper

@Immutable public class StreamHelper extends Object
Helper class for safe stream operations such as copying, closing, flushing, and converting between byte/char streams.
Author:
Philip Helger
  • Field Details

    • DEFAULT_BUFSIZE

      public static final int DEFAULT_BUFSIZE
      buffer size for copy operations
      See Also:
    • END_OF_STRING_MARKER

      public static final int END_OF_STRING_MARKER
      See Also:
    • MAX_SAFE_UTF_BYTES

      public static final int MAX_SAFE_UTF_BYTES
      The maximum number of bytes that readSafeUTF(DataInput) will allocate for a single string. This exists to prevent denial-of-service attacks via crafted serialized data that specifies a very large length value. The default is 64 MB.
      See Also:
  • Constructor Details

    • StreamHelper

      protected StreamHelper()
  • Method Details

    • createDefaultCopyBufferBytes

      @ReturnsMutableCopy public static byte @NonNull [] createDefaultCopyBufferBytes()
      Returns:
      A newly created copy buffer using DEFAULT_BUFSIZE. Never null.
      Since:
      9.3.6
    • createDefaultCopyBufferChars

      @ReturnsMutableCopy public static char @NonNull [] createDefaultCopyBufferChars()
      Returns:
      A newly created copy buffer using DEFAULT_BUFSIZE. Never null.
      Since:
      9.3.6
    • createReader

      public static @NonNull NonBlockingStringReader createReader(@NonNull String sText)
      Create a NonBlockingStringReader for the given text.
      Parameters:
      sText - The text to read from. May not be null.
      Returns:
      Never null.
    • createReader

      public static @NonNull NonBlockingStringReader createReader(char @NonNull [] aChars)
      Create a NonBlockingStringReader for the given char array.
      Parameters:
      aChars - The char array to read from. May not be null.
      Returns:
      Never null.
    • createReader

      public static @Nullable InputStreamReader createReader(@Nullable InputStream aIS, @NonNull Charset aCharset)
      Create an InputStreamReader wrapping the given input stream with the specified charset.
      Parameters:
      aIS - The input stream to wrap. May be null.
      aCharset - The charset to use. May not be null.
      Returns:
      null if the input stream is null.
    • createWriter

      public static @Nullable OutputStreamWriter createWriter(@Nullable OutputStream aOS, @NonNull Charset aCharset)
      Create an OutputStreamWriter wrapping the given output stream with the specified charset.
      Parameters:
      aOS - The output stream to wrap. May be null.
      aCharset - The charset to use. May not be null.
      Returns:
      null if the output stream is null.
    • isKnownEOFException

      public static boolean isKnownEOFException(@Nullable Throwable t)
      Check if the passed exception is a known EOF exception.
      Parameters:
      t - The throwable/exception to be checked. May be null.
      Returns:
      true if it is a user-created EOF exception
    • isKnownEOFException

      public static boolean isKnownEOFException(@Nullable Class<?> aClass)
      Check if the passed class is a known EOF exception class.
      Parameters:
      aClass - The class to be checked. May be null.
      Returns:
      true if it is a known EOF exception class.
    • internalGetPropagatableException

      protected static @Nullable Exception internalGetPropagatableException(@NonNull Exception ex)
    • closeWithoutFlush

      public static @NonNull ESuccess closeWithoutFlush(@WillClose @Nullable AutoCloseable aCloseable)
      Close the passed object, without trying to call flush on it.
      Parameters:
      aCloseable - The object to be closed. May be null.
      Returns:
      ESuccess.SUCCESS if the object was successfully closed.
    • close

      public static @NonNull ESuccess close(@WillClose @Nullable AutoCloseable aCloseable)
      Close the passed stream by encapsulating the declared IOException. If the passed object also implements the Flushable interface, it is tried to be flushed before it is closed.
      Parameters:
      aCloseable - The object to be closed. May be null.
      Returns:
      ESuccess if the object was successfully closed.
    • flush

      public static @NonNull ESuccess flush(@Nullable Flushable aFlushable)
      Flush the passed object encapsulating the declared IOException.
      Parameters:
      aFlushable - The flushable to be flushed. May be null.
      Returns:
      ESuccess.SUCCESS if the object was successfully flushed.
    • isBuffered

      public static boolean isBuffered(@Nullable InputStream aIS)
      Check if the passed input stream is already buffered.
      Parameters:
      aIS - The input stream to check. May be null.
      Returns:
      true if the stream is already buffered.
    • getBuffered

      public static @Nullable InputStream getBuffered(@Nullable InputStream aIS)
      Get a buffered version of the passed input stream. If the stream is already buffered, it is returned as-is.
      Parameters:
      aIS - The input stream to buffer. May be null.
      Returns:
      null if the input stream is null.
    • isBuffered

      public static boolean isBuffered(@Nullable OutputStream aOS)
      Check if the passed output stream is already buffered.
      Parameters:
      aOS - The output stream to check. May be null.
      Returns:
      true if the stream is already buffered.
    • getBuffered

      public static @Nullable OutputStream getBuffered(@Nullable OutputStream aOS)
      Get a buffered version of the passed output stream. If the stream is already buffered, it is returned as-is.
      Parameters:
      aOS - The output stream to buffer. May be null.
      Returns:
      null if the output stream is null.
    • isBuffered

      public static boolean isBuffered(@Nullable Reader aReader)
      Check if the passed reader is already buffered.
      Parameters:
      aReader - The reader to check. May be null.
      Returns:
      true if the reader is already buffered.
    • getBuffered

      public static @Nullable Reader getBuffered(@Nullable Reader aReader)
      Get a buffered version of the passed reader. If the reader is already buffered, it is returned as-is.
      Parameters:
      aReader - The reader to buffer. May be null.
      Returns:
      null if the reader is null.
    • isBuffered

      public static boolean isBuffered(@Nullable Writer aWriter)
      Check if the passed writer is already buffered.
      Parameters:
      aWriter - The writer to check. May be null.
      Returns:
      true if the writer is already buffered.
    • getBuffered

      public static @Nullable Writer getBuffered(@Nullable Writer aWriter)
      Get a buffered version of the passed writer. If the writer is already buffered, it is returned as-is.
      Parameters:
      aWriter - The writer to buffer. May be null.
      Returns:
      null if the writer is null.
    • copyInputStreamToOutputStream

      public static @NonNull ESuccess copyInputStreamToOutputStream(@WillClose @Nullable InputStream aIS, @WillNotClose @Nullable OutputStream aOS)
      Pass the content of the given input stream to the given output stream. The input stream is automatically closed, whereas the output stream stays open!
      Parameters:
      aIS - The input stream to read from. May be null. Automatically closed!
      aOS - The output stream to write to. May be null. Not automatically closed!
      Returns:
      ESuccess.SUCCESS if copying took place, ESuccess.FAILURE otherwise
    • copyInputStreamToOutputStreamAndCloseOS

      public static @NonNull ESuccess copyInputStreamToOutputStreamAndCloseOS(@WillClose @Nullable InputStream aIS, @WillClose @Nullable OutputStream aOS)
      Pass the content of the given input stream to the given output stream. Both the input stream and the output stream are automatically closed.
      Parameters:
      aIS - The input stream to read from. May be null. Automatically closed!
      aOS - The output stream to write to. May be null. Automatically closed!
      Returns:
      ESuccess.SUCCESS if copying took place, ESuccess.FAILURE otherwise
    • copyByteStream

      public static @NonNull StreamHelper.CopyByteStreamBuilder copyByteStream()
      Returns:
      A new StreamHelper.CopyByteStreamBuilder. Never null.
    • getAvailable

      public static int getAvailable(@Nullable InputStream aIS)
      Get the number of available bytes in the passed input stream.
      Parameters:
      aIS - The input stream to use. May be null.
      Returns:
      0 in case of an error or if the parameter was null.
    • getCopy

      public static @Nullable NonBlockingByteArrayOutputStream getCopy(@WillClose @NonNull InputStream aIS)
      Get a byte buffer with all the available content of the passed input stream.
      Parameters:
      aIS - The source input stream. May not be null.
      Returns:
      A new NonBlockingByteArrayOutputStream with all available content inside. The OutputStream must be closed by the caller since v10. Since v9.3.6 this method returns null if copying fails.
    • getCopyWithLimit

      public static @Nullable NonBlockingByteArrayOutputStream getCopyWithLimit(@WillClose @NonNull InputStream aIS, @Nonnegative long nLimit)
      Get a byte buffer with all the available content of the passed input stream.
      Parameters:
      aIS - The source input stream. May not be null.
      nLimit - The maximum number of bytes to be copied to the output stream. Must be ≥ 0.
      Returns:
      A new NonBlockingByteArrayOutputStream with all available content inside. The OutputStream must be closed by the caller since v10. Since v9.3.6 this method returns null if copying fails.
    • getAllBytes

      public static byte @Nullable [] getAllBytes(@Nullable IHasInputStream aISP)
      Read all bytes from the passed input stream into a byte array.
      Parameters:
      aISP - The input stream provider to read from. May be null .
      Returns:
      The byte array or null if the parameter or the resolved input stream is null.
    • getAllBytes

      public static byte @Nullable [] getAllBytes(@WillClose @Nullable InputStream aIS)
      Read all bytes from the passed input stream into a byte array.
      Parameters:
      aIS - The input stream to read from. May be null.
      Returns:
      The byte array or null if the input stream is null.
    • getAllBytesAsString

      public static @Nullable String getAllBytesAsString(@Nullable IHasInputStream aISP, @Nonempty @NonNull @Nonempty Charset aCharset)
      Read all bytes from the passed input stream into a string.
      Parameters:
      aISP - The input stream provider to read from. May be null .
      aCharset - The charset to use. May not be null .
      Returns:
      The String or null if the parameter or the resolved input stream is null.
    • getAllBytesAsString

      public static @Nullable String getAllBytesAsString(@WillClose @Nullable InputStream aIS, @Nonempty @NonNull @Nonempty Charset aCharset)
      Read all bytes from the passed input stream into a string.
      Parameters:
      aIS - The input stream to read from. May be null.
      aCharset - The charset to use. May not be null .
      Returns:
      The String or null if the input stream is null.
    • copyReaderToWriter

      public static @NonNull ESuccess copyReaderToWriter(@WillClose @Nullable Reader aReader, @WillNotClose @Nullable Writer aWriter)
      Pass the content of the given reader to the given writer. The reader is automatically closed, whereas the writer stays open!
      Parameters:
      aReader - The reader to read from. May be null. Automatically closed!
      aWriter - The writer to write to. May be null. Not automatically closed!
      Returns:
      ESuccess.SUCCESS if copying took place, ESuccess.FAILURE otherwise
    • copyReaderToWriterAndCloseWriter

      public static @NonNull ESuccess copyReaderToWriterAndCloseWriter(@WillClose @Nullable Reader aReader, @WillClose @Nullable Writer aWriter)
      Pass the content of the given reader to the given writer. The reader and the writer are automatically closed!
      Parameters:
      aReader - The reader to read from. May be null. Automatically closed!
      aWriter - The writer to write to. May be null. Automatically closed!
      Returns:
      ESuccess.SUCCESS if copying took place, ESuccess.FAILURE otherwise
    • copyCharStream

      public static @NonNull StreamHelper.CopyCharStreamBuilder copyCharStream()
      Returns:
      A new StreamHelper.CopyCharStreamBuilder. Never null.
    • getCopy

      public static @Nullable NonBlockingStringWriter getCopy(@WillClose @NonNull Reader aReader)
      Copy the content of the given reader into a new NonBlockingStringWriter. The reader is closed after the operation.
      Parameters:
      aReader - The reader to copy from. May not be null. Will be closed.
      Returns:
      null if copying failed.
    • getCopyWithLimit

      public static @Nullable NonBlockingStringWriter getCopyWithLimit(@WillClose @NonNull Reader aReader, @Nonnegative long nLimit)
      Copy at most the specified number of characters from the given reader into a new NonBlockingStringWriter. The reader is closed after the operation.
      Parameters:
      aReader - The reader to copy from. May not be null. Will be closed.
      nLimit - The maximum number of characters to copy. Must be ≥ 0.
      Returns:
      null if copying failed.
    • getAllCharacters

      public static char @Nullable [] getAllCharacters(@WillClose @Nullable Reader aReader)
      Read all characters from the passed reader into a char array.
      Parameters:
      aReader - The reader to read from. May be null.
      Returns:
      The character array or null if the reader is null.
    • getAllCharactersAsString

      public static @Nullable String getAllCharactersAsString(@WillClose @Nullable Reader aReader)
      Read all characters from the passed reader into a String.
      Parameters:
      aReader - The reader to read from. May be null.
      Returns:
      The character array or null if the reader is null.
    • writeStream

      public static @NonNull ESuccess writeStream(@WillClose @NonNull OutputStream aOS, byte @NonNull [] aBuf, @Nonnegative int nOfs, @Nonnegative int nLen)
      Write bytes to an OutputStream.
      Parameters:
      aOS - The output stream to write to. May not be null. Is closed independent of error or success.
      aBuf - The byte array from which is to be written. May not be null.
      nOfs - The 0-based index to the first byte in the array to be written. May not be < 0.
      nLen - The non-negative amount of bytes to be written. May not be < 0.
      Returns:
      ESuccess
    • writeStream

      public static @NonNull ESuccess writeStream(@WillClose @NonNull OutputStream aOS, byte @NonNull [] aBuf)
      Write bytes to an OutputStream.
      Parameters:
      aOS - The output stream to write to. May not be null. Is closed independent of error or success.
      aBuf - The byte array to be written. May not be null.
      Returns:
      ESuccess
    • writeStream

      public static @NonNull ESuccess writeStream(@WillClose @NonNull OutputStream aOS, @NonNull String sContent, @NonNull Charset aCharset)
      Write bytes to an OutputStream.
      Parameters:
      aOS - The output stream to write to. May not be null. Is closed independent of error or success.
      sContent - The string to be written. May not be null.
      aCharset - The charset to be used, to convert the String to a byte array.
      Returns:
      ESuccess
    • skipFully

      public static void skipFully(@NonNull InputStream aIS, @Nonnegative long nBytesToSkip) throws IOException
      Fully skip the passed amounts in the input stream. Only forward skipping is possible!
      Parameters:
      aIS - The input stream to skip in.
      nBytesToSkip - The number of bytes to skip. Must be ≥ 0.
      Throws:
      IOException - In case something goes wrong internally
    • readFully

      @Nonnegative public static int readFully(@NonNull InputStream aIS, byte @NonNull [] aBuffer) throws IOException
      Read the whole buffer from the input stream.
      Parameters:
      aIS - The input stream to read from. May not be null.
      aBuffer - The buffer to write to. May not be null. Must be ≥ than the content to be read.
      Returns:
      The number of read bytes
      Throws:
      IOException - In case reading fails
    • readFully

      @Nonnegative public static int readFully(@WillNotClose @NonNull InputStream aIS, byte @NonNull [] aBuffer, @Nonnegative int nOfs, @Nonnegative int nLen) throws IOException
      Read the whole buffer from the input stream.
      Parameters:
      aIS - The input stream to read from. May not be null.
      aBuffer - The buffer to write to. May not be null. Must be ≥ than the content to be read.
      nOfs - The offset into the destination buffer to use. May not be < 0.
      nLen - The number of bytes to read into the destination buffer to use. May not be < 0.
      Returns:
      The number of read bytes
      Throws:
      IOException - In case reading fails
    • readUntilEOF

      public static void readUntilEOF(@WillClose @NonNull InputStream aIS, @NonNull ObjIntConsumer<? super byte[]> aConsumer) throws IOException
      Read the input stream until EOF, passing each chunk to the consumer. The stream is closed after the operation. Uses the default buffer size.
      Parameters:
      aIS - The input stream to read from. May not be null. Will be closed.
      aConsumer - The consumer receiving each read chunk and the number of bytes read. May not be null.
      Throws:
      IOException - In case of an I/O error.
    • readUntilEOF

      public static void readUntilEOF(@WillClose @NonNull InputStream aIS, byte @NonNull [] aBuffer, @NonNull ObjIntConsumer<? super byte[]> aConsumer) throws IOException
      Read the input stream until EOF, passing each chunk to the consumer. The stream is closed after the operation.
      Parameters:
      aIS - The input stream to read from. May not be null. Will be closed.
      aBuffer - The buffer to use for reading. May not be null.
      aConsumer - The consumer receiving each read chunk and the number of bytes read. May not be null.
      Throws:
      IOException - In case of an I/O error.
    • readUntilEOF

      public static void readUntilEOF(@WillClose @NonNull Reader aReader, @NonNull ObjIntConsumer<? super char[]> aConsumer) throws IOException
      Read the reader until EOF, passing each chunk to the consumer. The reader is closed after the operation. Uses the default buffer size.
      Parameters:
      aReader - The reader to read from. May not be null. Will be closed.
      aConsumer - The consumer receiving each read chunk and the number of chars read. May not be null.
      Throws:
      IOException - In case of an I/O error.
    • readUntilEOF

      public static void readUntilEOF(@WillClose @NonNull Reader aReader, char @NonNull [] aBuffer, @NonNull ObjIntConsumer<? super char[]> aConsumer) throws IOException
      Read the reader until EOF, passing each chunk to the consumer. The reader is closed after the operation.
      Parameters:
      aReader - The reader to read from. May not be null. Will be closed.
      aBuffer - The buffer to use for reading. May not be null.
      aConsumer - The consumer receiving each read chunk and the number of chars read. May not be null.
      Throws:
      IOException - In case of an I/O error.
    • checkForInvalidFilterInputStream

      public static @Nullable InputStream checkForInvalidFilterInputStream(@Nullable InputStream aIS)
      Check if the passed input stream is a FilterInputStream with a null contained input stream. This can happen when a JAR URL with a directory path that does not end with a slash is resolved.
      Parameters:
      aIS - The input stream to check. May be null.
      Returns:
      null if the input stream is invalid or null, the passed stream otherwise.
    • writeSafeUTF

      public static void writeSafeUTF(@NonNull DataOutput aDO, @Nullable String sStr) throws IOException
      Because DataOutputStream.writeUTF(String) has a limit of 64KB this methods provides a similar solution but simply writing the bytes.
      Parameters:
      aDO - DataOutput to write to. May not be null.
      sStr - The string to be written. May be null.
      Throws:
      IOException - on write error
      See Also:
    • readSafeUTF

      public static @Nullable String readSafeUTF(@NonNull DataInput aDI) throws IOException
      Because DataOutputStream.writeUTF(String) has a limit of 64KB this methods provides a similar solution for reading like DataInputStream.readUTF() but what was written in writeSafeUTF(DataOutput, String).
      Parameters:
      aDI - DataInput to read from. May not be null.
      Returns:
      The read string. May be null.
      Throws:
      IOException - on read error
      See Also: