Write a Java Program to Convert the InputStream into Byte Array

Java Program to Convert the InputStream into Byte Array

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Convert the InputStream into Byte Array
Java Program to Convert the InputStream into Byte Array

Write a Java Program to Convert the InputStream into Byte Array

PROGRAM: Java Program to Convert the InputStream into Byte Array

/*Java Program to Convert the InputStream into Byte Array*/

1: Java Program to Convert InputStream to Byte Array

import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;

public class Main {

public static void main(String args[]) {

try {

// create an input stream
byte[] input = {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(input);
System.out.println(“Input Stream: ” + stream);

// convert the input stream to byte array
byte[] array = stream.readAllBytes();
System.out.println(“Byte Array: ” + Arrays.toString(array));

stream.close();
}

catch (Exception e) {
e.getStackTrace();
}
}
}

 2: Convert InputStream to Byte Array using Output Stream

import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class Main {

public static void main(String args[]) {

try {

// create an input stream
byte[] input = {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(input);
System.out.println(“Input Stream: ” + stream);

// create an output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
// create a byte array to store input stream
byte[] array = new byte[4];
int i;

// read all data from input stream to array
while ((i = stream.read(array, 0, array.length)) != -1) {

// write all data from array to output
output.write(array, 0, i);
}

byte[] data = output.toByteArray();

// convert the input stream to byte array
System.out.println(“Byte Array: ” + Arrays.toString(data));
stream.close();
}

catch (Exception e) {
e.getStackTrace();
}
}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *