Package com.helger.base.io.stream
Class StreamHelper
java.lang.Object
com.helger.base.io.stream.StreamHelper
Helper class for safe stream operations such as copying, closing, flushing,
and converting between byte/char streams.
- Author:
- Philip Helger
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classA simple builder to copy an InputStream (StreamHelper.CopyByteStreamBuilder.from(InputStream)) to an OutputStream (StreamHelper.CopyByteStreamBuilder.to(OutputStream)) with certain parameters.static classA simple builder to copy a Reader (StreamHelper.CopyCharStreamBuilder.from(Reader)) to an Writer (StreamHelper.CopyCharStreamBuilder.to(Writer)) with certain parameters. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intbuffer size for copy operationsstatic final intstatic final intThe maximum number of bytes thatreadSafeUTF(DataInput)will allocate for a single string. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic @Nullable InputStreamcheckForInvalidFilterInputStream(@Nullable InputStream aIS) Check if the passed input stream is aFilterInputStreamwith anullcontained input stream.static @NonNull ESuccessclose(@Nullable AutoCloseable aCloseable) Close the passed stream by encapsulating the declaredIOException.static @NonNull ESuccesscloseWithoutFlush(@Nullable AutoCloseable aCloseable) Close the passed object, without trying to call flush on it.static @NonNull StreamHelper.CopyByteStreamBuilderstatic @NonNull StreamHelper.CopyCharStreamBuilderstatic @NonNull ESuccesscopyInputStreamToOutputStream(@Nullable InputStream aIS, @Nullable OutputStream aOS) Pass the content of the given input stream to the given output stream.static @NonNull ESuccesscopyInputStreamToOutputStreamAndCloseOS(@Nullable InputStream aIS, @Nullable OutputStream aOS) Pass the content of the given input stream to the given output stream.static @NonNull ESuccesscopyReaderToWriter(@Nullable Reader aReader, @Nullable Writer aWriter) Pass the content of the given reader to the given writer.static @NonNull ESuccesscopyReaderToWriterAndCloseWriter(@Nullable Reader aReader, @Nullable Writer aWriter) Pass the content of the given reader to the given writer.static byte @NonNull []static char @NonNull []static @NonNull NonBlockingStringReadercreateReader(char @NonNull [] aChars) Create aNonBlockingStringReaderfor the given char array.static @Nullable InputStreamReadercreateReader(@Nullable InputStream aIS, @NonNull Charset aCharset) Create anInputStreamReaderwrapping the given input stream with the specified charset.static @NonNull NonBlockingStringReadercreateReader(@NonNull String sText) Create aNonBlockingStringReaderfor the given text.static @Nullable OutputStreamWritercreateWriter(@Nullable OutputStream aOS, @NonNull Charset aCharset) Create anOutputStreamWriterwrapping the given output stream with the specified charset.static @NonNull ESuccessFlush the passed object encapsulating the declaredIOException.static byte @Nullable []getAllBytes(@Nullable IHasInputStream aISP) Read all bytes from the passed input stream into a byte array.static byte @Nullable []getAllBytes(@Nullable InputStream aIS) Read all bytes from the passed input stream into a byte array.static @Nullable StringgetAllBytesAsString(@Nullable IHasInputStream aISP, @NonNull @Nonempty Charset aCharset) Read all bytes from the passed input stream into a string.static @Nullable StringgetAllBytesAsString(@Nullable InputStream aIS, @NonNull @Nonempty Charset aCharset) Read all bytes from the passed input stream into a string.static char @Nullable []getAllCharacters(@Nullable Reader aReader) Read all characters from the passed reader into a char array.static @Nullable StringgetAllCharactersAsString(@Nullable Reader aReader) Read all characters from the passed reader into a String.static intgetAvailable(@Nullable InputStream aIS) Get the number of available bytes in the passed input stream.static @Nullable InputStreamgetBuffered(@Nullable InputStream aIS) Get a buffered version of the passed input stream.static @Nullable OutputStreamgetBuffered(@Nullable OutputStream aOS) Get a buffered version of the passed output stream.static @Nullable ReadergetBuffered(@Nullable Reader aReader) Get a buffered version of the passed reader.static @Nullable WritergetBuffered(@Nullable Writer aWriter) Get a buffered version of the passed writer.static @Nullable NonBlockingByteArrayOutputStreamgetCopy(@NonNull InputStream aIS) Get a byte buffer with all the available content of the passed input stream.static @Nullable NonBlockingStringWriterCopy the content of the given reader into a newNonBlockingStringWriter.static @Nullable NonBlockingByteArrayOutputStreamgetCopyWithLimit(@NonNull InputStream aIS, long nLimit) Get a byte buffer with all the available content of the passed input stream.static @Nullable NonBlockingStringWritergetCopyWithLimit(@NonNull Reader aReader, long nLimit) Copy at most the specified number of characters from the given reader into a newNonBlockingStringWriter.protected static @Nullable ExceptioninternalGetPropagatableException(@NonNull Exception ex) static booleanisBuffered(@Nullable InputStream aIS) Check if the passed input stream is already buffered.static booleanisBuffered(@Nullable OutputStream aOS) Check if the passed output stream is already buffered.static booleanisBuffered(@Nullable Reader aReader) Check if the passed reader is already buffered.static booleanisBuffered(@Nullable Writer aWriter) Check if the passed writer is already buffered.static booleanisKnownEOFException(@Nullable Class<?> aClass) Check if the passed class is a known EOF exception class.static booleanisKnownEOFException(@Nullable Throwable t) Check if the passed exception is a known EOF exception.static intreadFully(@NonNull InputStream aIS, byte @NonNull [] aBuffer) Read the whole buffer from the input stream.static intreadFully(@NonNull InputStream aIS, byte @NonNull [] aBuffer, int nOfs, int nLen) Read the whole buffer from the input stream.static @Nullable StringreadSafeUTF(@NonNull DataInput aDI) BecauseDataOutputStream.writeUTF(String)has a limit of 64KB this methods provides a similar solution for reading likeDataInputStream.readUTF()but what was written inwriteSafeUTF(DataOutput, String).static voidreadUntilEOF(@NonNull InputStream aIS, byte @NonNull [] aBuffer, @NonNull ObjIntConsumer<? super byte[]> aConsumer) Read the input stream until EOF, passing each chunk to the consumer.static voidreadUntilEOF(@NonNull InputStream aIS, @NonNull ObjIntConsumer<? super byte[]> aConsumer) Read the input stream until EOF, passing each chunk to the consumer.static voidreadUntilEOF(@NonNull Reader aReader, char @NonNull [] aBuffer, @NonNull ObjIntConsumer<? super char[]> aConsumer) Read the reader until EOF, passing each chunk to the consumer.static voidreadUntilEOF(@NonNull Reader aReader, @NonNull ObjIntConsumer<? super char[]> aConsumer) Read the reader until EOF, passing each chunk to the consumer.static voidskipFully(@NonNull InputStream aIS, long nBytesToSkip) Fully skip the passed amounts in the input stream.static voidwriteSafeUTF(@NonNull DataOutput aDO, @Nullable String sStr) BecauseDataOutputStream.writeUTF(String)has a limit of 64KB this methods provides a similar solution but simply writing the bytes.static @NonNull ESuccesswriteStream(@NonNull OutputStream aOS, byte @NonNull [] aBuf) Write bytes to anOutputStream.static @NonNull ESuccesswriteStream(@NonNull OutputStream aOS, byte @NonNull [] aBuf, int nOfs, int nLen) Write bytes to anOutputStream.static @NonNull ESuccesswriteStream(@NonNull OutputStream aOS, @NonNull String sContent, @NonNull Charset aCharset) Write bytes to anOutputStream.
-
Field Details
-
DEFAULT_BUFSIZE
public static final int DEFAULT_BUFSIZEbuffer 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_BYTESThe maximum number of bytes thatreadSafeUTF(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. Nevernull. - Since:
- 9.3.6
-
createDefaultCopyBufferChars
@ReturnsMutableCopy public static char @NonNull [] createDefaultCopyBufferChars()- Returns:
- A newly created copy buffer using
DEFAULT_BUFSIZE. Nevernull. - Since:
- 9.3.6
-
createReader
Create aNonBlockingStringReaderfor the given text.- Parameters:
sText- The text to read from. May not benull.- Returns:
- Never
null.
-
createReader
Create aNonBlockingStringReaderfor the given char array.- Parameters:
aChars- The char array to read from. May not benull.- Returns:
- Never
null.
-
createReader
public static @Nullable InputStreamReader createReader(@Nullable InputStream aIS, @NonNull Charset aCharset) Create anInputStreamReaderwrapping the given input stream with the specified charset.- Parameters:
aIS- The input stream to wrap. May benull.aCharset- The charset to use. May not benull.- Returns:
nullif the input stream isnull.
-
createWriter
public static @Nullable OutputStreamWriter createWriter(@Nullable OutputStream aOS, @NonNull Charset aCharset) Create anOutputStreamWriterwrapping the given output stream with the specified charset.- Parameters:
aOS- The output stream to wrap. May benull.aCharset- The charset to use. May not benull.- Returns:
nullif the output stream isnull.
-
isKnownEOFException
Check if the passed exception is a known EOF exception.- Parameters:
t- The throwable/exception to be checked. May benull.- Returns:
trueif it is a user-created EOF exception
-
isKnownEOFException
Check if the passed class is a known EOF exception class.- Parameters:
aClass- The class to be checked. May benull.- Returns:
trueif it is a known EOF exception class.
-
internalGetPropagatableException
-
closeWithoutFlush
Close the passed object, without trying to call flush on it.- Parameters:
aCloseable- The object to be closed. May benull.- Returns:
ESuccess.SUCCESSif the object was successfully closed.
-
close
Close the passed stream by encapsulating the declaredIOException. If the passed object also implements theFlushableinterface, it is tried to be flushed before it is closed.- Parameters:
aCloseable- The object to be closed. May benull.- Returns:
ESuccessif the object was successfully closed.
-
flush
Flush the passed object encapsulating the declaredIOException.- Parameters:
aFlushable- The flushable to be flushed. May benull.- Returns:
ESuccess.SUCCESSif the object was successfully flushed.
-
isBuffered
Check if the passed input stream is already buffered.- Parameters:
aIS- The input stream to check. May benull.- Returns:
trueif the stream is already buffered.
-
getBuffered
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 benull.- Returns:
nullif the input stream isnull.
-
isBuffered
Check if the passed output stream is already buffered.- Parameters:
aOS- The output stream to check. May benull.- Returns:
trueif the stream is already buffered.
-
getBuffered
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 benull.- Returns:
nullif the output stream isnull.
-
isBuffered
Check if the passed reader is already buffered.- Parameters:
aReader- The reader to check. May benull.- Returns:
trueif the reader is already buffered.
-
getBuffered
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 benull.- Returns:
nullif the reader isnull.
-
isBuffered
Check if the passed writer is already buffered.- Parameters:
aWriter- The writer to check. May benull.- Returns:
trueif the writer is already buffered.
-
getBuffered
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 benull.- Returns:
nullif the writer isnull.
-
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 benull. Automatically closed!aOS- The output stream to write to. May benull. Not automatically closed!- Returns:
if copying took place,ESuccess.SUCCESSotherwiseESuccess.FAILURE
-
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 benull. Automatically closed!aOS- The output stream to write to. May benull. Automatically closed!- Returns:
if copying took place,ESuccess.SUCCESSotherwiseESuccess.FAILURE
-
copyByteStream
- Returns:
- A new
StreamHelper.CopyByteStreamBuilder. Nevernull.
-
getAvailable
Get the number of available bytes in the passed input stream.- Parameters:
aIS- The input stream to use. May benull.- 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 benull.- Returns:
- A new
NonBlockingByteArrayOutputStreamwith all available content inside. TheOutputStreammust be closed by the caller since v10. Since v9.3.6 this method returnsnullif 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 benull.nLimit- The maximum number of bytes to be copied to the output stream. Must be ≥ 0.- Returns:
- A new
NonBlockingByteArrayOutputStreamwith all available content inside. TheOutputStreammust be closed by the caller since v10. Since v9.3.6 this method returnsnullif copying fails.
-
getAllBytes
Read all bytes from the passed input stream into a byte array.- Parameters:
aISP- The input stream provider to read from. May benull.- Returns:
- The byte array or
nullif the parameter or the resolved input stream isnull.
-
getAllBytes
Read all bytes from the passed input stream into a byte array.- Parameters:
aIS- The input stream to read from. May benull.- Returns:
- The byte array or
nullif the input stream isnull.
-
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 benull.aCharset- The charset to use. May not benull.- Returns:
- The String or
nullif the parameter or the resolved input stream isnull.
-
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 benull.aCharset- The charset to use. May not benull.- Returns:
- The String or
nullif the input stream isnull.
-
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 benull. Automatically closed!aWriter- The writer to write to. May benull. Not automatically closed!- Returns:
if copying took place,ESuccess.SUCCESSotherwiseESuccess.FAILURE
-
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 benull. Automatically closed!aWriter- The writer to write to. May benull. Automatically closed!- Returns:
if copying took place,ESuccess.SUCCESSotherwiseESuccess.FAILURE
-
copyCharStream
- Returns:
- A new
StreamHelper.CopyCharStreamBuilder. Nevernull.
-
getCopy
Copy the content of the given reader into a newNonBlockingStringWriter. The reader is closed after the operation.- Parameters:
aReader- The reader to copy from. May not benull. Will be closed.- Returns:
nullif 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 newNonBlockingStringWriter. The reader is closed after the operation.- Parameters:
aReader- The reader to copy from. May not benull. Will be closed.nLimit- The maximum number of characters to copy. Must be ≥ 0.- Returns:
nullif copying failed.
-
getAllCharacters
Read all characters from the passed reader into a char array.- Parameters:
aReader- The reader to read from. May benull.- Returns:
- The character array or
nullif the reader isnull.
-
getAllCharactersAsString
Read all characters from the passed reader into a String.- Parameters:
aReader- The reader to read from. May benull.- Returns:
- The character array or
nullif the reader isnull.
-
writeStream
public static @NonNull ESuccess writeStream(@WillClose @NonNull OutputStream aOS, byte @NonNull [] aBuf, @Nonnegative int nOfs, @Nonnegative int nLen) Write bytes to anOutputStream.- Parameters:
aOS- The output stream to write to. May not benull. Is closed independent of error or success.aBuf- The byte array from which is to be written. May not benull.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 anOutputStream.- Parameters:
aOS- The output stream to write to. May not benull. Is closed independent of error or success.aBuf- The byte array to be written. May not benull.- Returns:
ESuccess
-
writeStream
public static @NonNull ESuccess writeStream(@WillClose @NonNull OutputStream aOS, @NonNull String sContent, @NonNull Charset aCharset) Write bytes to anOutputStream.- Parameters:
aOS- The output stream to write to. May not benull. Is closed independent of error or success.sContent- The string to be written. May not benull.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 benull.aBuffer- The buffer to write to. May not benull. 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 benull.aBuffer- The buffer to write to. May not benull. 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 benull. Will be closed.aConsumer- The consumer receiving each read chunk and the number of bytes read. May not benull.- 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 benull. Will be closed.aBuffer- The buffer to use for reading. May not benull.aConsumer- The consumer receiving each read chunk and the number of bytes read. May not benull.- 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 benull. Will be closed.aConsumer- The consumer receiving each read chunk and the number of chars read. May not benull.- 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 benull. Will be closed.aBuffer- The buffer to use for reading. May not benull.aConsumer- The consumer receiving each read chunk and the number of chars read. May not benull.- Throws:
IOException- In case of an I/O error.
-
checkForInvalidFilterInputStream
Check if the passed input stream is aFilterInputStreamwith anullcontained 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 benull.- Returns:
nullif the input stream is invalid ornull, the passed stream otherwise.
-
writeSafeUTF
BecauseDataOutputStream.writeUTF(String)has a limit of 64KB this methods provides a similar solution but simply writing the bytes.- Parameters:
aDO-DataOutputto write to. May not benull.sStr- The string to be written. May benull.- Throws:
IOException- on write error- See Also:
-
readSafeUTF
BecauseDataOutputStream.writeUTF(String)has a limit of 64KB this methods provides a similar solution for reading likeDataInputStream.readUTF()but what was written inwriteSafeUTF(DataOutput, String).- Parameters:
aDI-DataInputto read from. May not benull.- Returns:
- The read string. May be
null. - Throws:
IOException- on read error- See Also:
-