Package com.guinetik.rr.util
Class StreamUtils
- java.lang.Object
-
- com.guinetik.rr.util.StreamUtils
-
public final class StreamUtils extends Object
Utility class for safe input stream operations with proper resource management.This class provides static methods for reading input streams into strings, ensuring proper cleanup of resources even when exceptions occur.
Reading Input Streams
// Read an input stream to string InputStream is = connection.getInputStream(); String content = StreamUtils.readInputStreamAsString(is); // Read error stream (returns null if unavailable) InputStream errorStream = connection.getErrorStream(); String error = StreamUtils.readErrorStream(errorStream); if (error != null) { System.err.println("Error response: " + error); }Usage in HTTP Response Handling
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int status = conn.getResponseCode(); if (status >= 200 && status < 300) { String body = StreamUtils.readInputStreamAsString(conn.getInputStream()); // Process successful response } else { String error = StreamUtils.readErrorStream(conn.getErrorStream()); // Handle error response }- Since:
- 1.0.0
- Author:
- guinetik <guinetik@gmail.com>
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static StringreadErrorStream(InputStream errorStream)Attempts to read from an error stream, handling possible exceptions gracefully.static StringreadInputStreamAsString(InputStream is)Reads an input stream into a string, handling resource cleanup properly.
-
-
-
Method Detail
-
readInputStreamAsString
public static String readInputStreamAsString(InputStream is) throws IOException
Reads an input stream into a string, handling resource cleanup properly. This method ensures the Scanner is properly closed after reading.- Parameters:
is- The input stream to read- Returns:
- The string contents of the stream
- Throws:
IOException- If an I/O error occurs
-
readErrorStream
public static String readErrorStream(InputStream errorStream)
Attempts to read from an error stream, handling possible exceptions gracefully. This method ensures the Scanner is properly closed after reading.- Parameters:
errorStream- The error stream to read- Returns:
- The string contents of the stream, or null if not available
-
-