Java-programma om de InputStream om te zetten in Byte Array

In dit voorbeeld zullen we leren om een ​​invoerstroom te converteren naar de byte-array in Java.

Om dit voorbeeld te begrijpen, moet u kennis hebben van de volgende Java-programmeeronderwerpen:

  • Java InputStream-klasse
  • Java ByteArrayInputStream-klasse
  • Java ByteArrayOutputStream-klasse

Voorbeeld 1: Java-programma om InputStream naar Byte Array te converteren

 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(); ) ) )

Uitvoer

 Invoerstroom: java.io.ByteArrayInputStream@27082746 Byte Array: (1, 2, 3, 4)

In het bovenstaande voorbeeld hebben we een invoerstroom gemaakt met de naam stream. Let op de lijn,

 byte() array = stream.readAllBytes();

Hier readAllBytes()retourneert de methode alle gegevens uit de stream en slaat deze op in de byte-array.

Opmerking : we hebben de Arrays.toString()methode gebruikt om de hele array in een string te converteren.

Voorbeeld 2: Converteer InputStream naar Byte Array met behulp van 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(); ) ) )

Uitvoer

 Invoerstroom: java.io.ByteArrayInputStream@27082746 Byte Array: (1, 2, 3, 4)

In het bovenstaande voorbeeld hebben we een invoerstroom gemaakt van de array-invoer. Let op de uitdrukking,

 stream.read(array, 0, array.length)

Hier worden alle elementen uit de stream in een array opgeslagen, beginnend bij index 0 . Vervolgens slaan we alle elementen van de array op in de outputstroom met de naam output.

 output.write(array, 0, i)

Ten slotte noemen we de toByteArray()methode van de ByteArrayOutputStreamklasse om de uitvoerstroom om te zetten in een byte-array met de naam data.

Interessante artikelen...