package fr.freydierepatrice.instrument.sample;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import org.apache.log4j.Logger;

public class RandomAccessFileInputStream extends InputStream {

	private static Logger logger = Logger
			.getLogger(RandomAccessFileInputStream.class);

	private RandomAccessFile raf;

	public RandomAccessFileInputStream(File file) throws IOException {
		raf = new RandomAccessFile(file, "r");
	}

	@Override
	public int read() throws IOException {
		return raf.read();
	}

	@Override
	public int read(byte[] b) throws IOException {
		return raf.read(b);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return raf.read(b, off, len);
	}

	@Override
	public boolean markSupported() {
		return true;
	}

	private long markedPos = 0;

	@Override
	public synchronized void mark(int readlimit) {
		try {
			markedPos = raf.getFilePointer();
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	@Override
	public synchronized void reset() throws IOException {
		raf.seek(markedPos);
	}

	@Override
	public void close() throws IOException {
		raf.close();
	}

}
