Equivalent to Java's built-in method InputStream#readAllBytes(). But the latter has a bug in Java 11 (fixed only in Java 14+). This method can be removed when we upgrade to Java 17+.
(InputStream in)
| 38 | * <p>This method can be removed when we upgrade to Java 17+. |
| 39 | */ |
| 40 | public static byte[] toByteArray(InputStream in) throws IOException { |
| 41 | int estimatedSize = Math.max(in.available(), 1024); |
| 42 | try (ByteArrayOutputStream out = new ByteArrayOutputStream(estimatedSize)) { |
| 43 | byte[] buffer = new byte[Math.min(estimatedSize, 4096)]; |
| 44 | |
| 45 | int readCount; |
| 46 | while ((readCount = in.read(buffer)) != -1) { |
| 47 | out.write(buffer, 0, readCount); |
| 48 | } |
| 49 | return out.toByteArray(); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public static String toString(InputStream in) throws IOException { |
| 54 | return new String(toByteArray(in), UTF_8); |