Programming Tips - Java: Read from an array of bytes like I read from a file

Date: 2012feb9 Update: 2025oct7 Language: Java Keywords: iterate Q. Java: Read from an array of bytes like I read from a file A. Use ByteBuffer. Shown in a full example:
import java.nio.ByteBuffer; import java.nio.BufferUnderflowException; import java.util.Arrays; class Demo { public static final void main(String []args) { byte [] data = { 00, 11, 22, 33, 44 }; ByteBuffer bb = ByteBuffer.wrap(data); // Create a ByteBuffer around the array System.out.println("data=" + Arrays.toString(data)); byte b; for (;;) { try { b = bb.get(); System.out.println("read b=" + b); } catch (BufferUnderflowException ex) { // EOF break; } } } }
Output:
data=[0, 11, 22, 33, 44] read b=0 read b=11 read b=22 read b=33 read b=44
If you just want to look thru a byte array do this:
for (byte b : data) { // Do something with b }