o7planning

Java ByteArrayInputStream Tutorial with Examples

  1. ByteArrayInputStream
  2. Examples

1. ByteArrayInputStream

ByteArrayInputStream is a subclass of InputStream. True to the name, ByteArrayInputStream is used to read a byte array by way of a InputStream.
ByteArrayInputStream constructors
ByteArrayInputStream​(byte[] buf)

ByteArrayInputStream​(byte[] buf, int offset, int length)
ByteArrayInputStream(byte[] buf) constructor creates a ByteArrayInputStream object to read a byte array.
ByteArrayInputStream(byte[] buf, int offset, int length) constructor creates a ByteArrayInputStream object to read a byte array from index offset to offset+length.
All methods of ByteArrayInputStream are inherited from InputStream.
Methods
int available()  
void close()  
void mark​(int readAheadLimit)  
boolean markSupported()  
int read()  
int read​(byte[] b, int off, int len)  
void reset()  
long skip​(long n)

2. Examples

Example: Reading a byte array in the way of an InputStream:
ByteArrayInputStreamEx1.java
package org.o7planning.bytearrayinputstream.ex;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInputStreamEx1 {

    public static void main(String[] args) throws IOException {

        byte[] byteArray = new byte[] {84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 120, 116};

        ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
        
        int b;
        while((b = is.read()) != -1) {
            // Convert byte to character.
            char ch = (char) b;
            System.out.println(b + " --> " + ch);
        }
    }
}
Output:
84 --> T
104 --> h
105 --> i
115 --> s
32 -->  
105 --> i
115 --> s
32 -->  
116 --> t
101 --> e
120 --> x
116 --> t
Basically, all ByteArrayInputStream's methods are inherited from InputStream, so you can find more examples of how to use these methods in the article below:

Java IO Tutorials

Show More