Java: Input/Output Streams

(Last Updated On: )

This page is to give some basic examples of how to convert OutputStreams to InputStreams and vise versa.

Maven:

<dependency>
	<groupId>org.logback-extensions</groupId>
	<artifactId>logback-ext-loggly</artifactId>
	<version>0.1.4</version>
</dependency>

To convert an InputStream to OutputStream we can do it using IoUtils.copy as demonstrated below.

import ch.qos.logback.ext.loggly.io.IoUtils;
import java.io.InputStream;

InputStream input = ##INPUTSTREAM##;

//Convert InputStream to OutputStream

try (FileOutputStream out = new FileOutputStream(file)) {
	IoUtils.copy(input, out);
} catch (final IOException e) {
}

To convert a ByteArrayOutputStream to a ByteArrayInputStream we can do it as demonstrated below.

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//Convert to ByteArrayInputStream
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());