import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Stack; /** * Utility class for reading raw data from a file. * Does not extend InputStream, but does implement most of its methods. */ public class HexInputStream { /** The InputStream this stream is based on. */ private volatile InputStream dis; /** The current position of this stream. */ private volatile long currPos; /** Get the current position of this stream. */ public long getPosition(){ return this.currPos; } /** * Sets the position of this stream. * @param newPos The desired position of the stream. * @throws IOException when the given position cannot be reached */ public void setPosition(long newPos) throws IOException{ this.skip(newPos - currPos); } /** Convenience method for {@link #setPosition(long)}. */ public void goTo(long pos) throws IOException{ this.setPosition(pos); } /** The stack of saved positions for this stream. */ private Stack positionStack; /** * Creates a new HexInputStream, based off another InputStream. * The 0-position of the new stream is the current position of the * given stream. * @param baseInputStream The InputStream to base the new HexInputStream on. */ public HexInputStream(InputStream baseInputStream) { this.dis = baseInputStream; this.currPos = 0; this.positionStack = new Stack(); } /** * Creates a new HexInputStream for reading a file. * @param String The name of the file to read. * @throws FileNotFoundException If the given file does not exist. */ public HexInputStream(String filename) throws FileNotFoundException { this.dis = new DataInputStream(new FileInputStream(new File(filename))); this.currPos = 0; this.positionStack = new Stack(); } /** * Returns an estimate of the number of bytes left to read until the EOF. * See {@link InputStream#available} */ public int available() throws IOException{ return dis.available(); } /** Read the next byte from a file. If the EOF has been reached, -1 is returned */ public int read() throws IOException{ int b = dis.read(); if(b != -1) currPos++; return b; } /** Read an array of bytes from this stream */ public int[] readBytes(int length) throws IOException{ int[] data = new int[length]; for(int i=0; i