Byte[] to InputStream or OutputStream in java

Byte[] to InputStream or OutputStream in java

To convert a byte[] to an InputStream in Java, you can use the ByteArrayInputStream class. Conversely, to write a byte[] to an OutputStream, you can use the ByteArrayOutputStream class. Here's how you can do both:

  • Convert a byte[] to an InputStream:
import java.io.ByteArrayInputStream; import java.io.InputStream; public class ByteArrayToInputStream { public static void main(String[] args) { byte[] byteArray = "Hello, World!".getBytes(); // Convert byte[] to InputStream InputStream inputStream = new ByteArrayInputStream(byteArray); // Now you can use the inputStream to read data from the byte array. // For example: // int data = inputStream.read(); // ... } } 

In this example, we create a ByteArrayInputStream from a byte[], and then you can read data from the InputStream as needed.

  • Write a byte[] to an OutputStream:
import java.io.ByteArrayOutputStream; import java.io.OutputStream; public class ByteArrayToOutputStream { public static void main(String[] args) { byte[] byteArray = "Hello, World!".getBytes(); // Create a ByteArrayOutputStream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Write the byte[] to the OutputStream outputStream.write(byteArray, 0, byteArray.length); // Now you can use the outputStream to access the written data. // For example: // byte[] resultByteArray = outputStream.toByteArray(); // ... } } 

In this example, we create a ByteArrayOutputStream, write the byte[] to it using the write method, and then you can access the written data, or convert it to a byte[] as needed.

These examples demonstrate how to convert between a byte[] and InputStream or OutputStream. Depending on your use case, you can choose the appropriate approach for reading or writing byte data.


More Tags

videochat ecdh administrator uialertcontroller datetime-format cross-validation updating digits threadpool entity-framework-4.1

More Java Questions

More Physical chemistry Calculators

More Transportation Calculators

More Bio laboratory Calculators

More Tax and Salary Calculators