X-Git-Url: http://git.nikiroo.be/?p=fanfix.git;a=blobdiff_plain;f=src%2Fbe%2Fnikiroo%2Futils%2Fstreams%2FMarkableFileInputStream.java;fp=src%2Fbe%2Fnikiroo%2Futils%2Fstreams%2FMarkableFileInputStream.java;h=7622b24f5af52e6234f446f88b0500d88f31eb3f;hp=0000000000000000000000000000000000000000;hb=d46b7b96f94e88a776bcd2dfd756549ffb300cc9;hpb=c9994f27667bc421bcd448d39e55774fddf5c431 diff --git a/src/be/nikiroo/utils/streams/MarkableFileInputStream.java b/src/be/nikiroo/utils/streams/MarkableFileInputStream.java new file mode 100644 index 0000000..7622b24 --- /dev/null +++ b/src/be/nikiroo/utils/streams/MarkableFileInputStream.java @@ -0,0 +1,66 @@ +package be.nikiroo.utils.streams; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + +/** + * This is a markable (and thus reset-able) stream that you can create from a + * FileInputStream. + * + * @author niki + */ +public class MarkableFileInputStream extends FilterInputStream { + private FileChannel channel; + private long mark = 0; + + /** + * Create a new {@link MarkableFileInputStream} from this file. + * + * @param file + * the {@link File} to wrap + * + * @throws FileNotFoundException + * if the {@link File} cannot be found + */ + public MarkableFileInputStream(File file) throws FileNotFoundException { + this(new FileInputStream(file)); + } + + /** + * Create a new {@link MarkableFileInputStream} from this stream. + * + * @param in + * the original {@link FileInputStream} to wrap + */ + public MarkableFileInputStream(FileInputStream in) { + super(in); + channel = in.getChannel(); + } + + @Override + public boolean markSupported() { + return true; + } + + @Override + public synchronized void mark(int readlimit) { + try { + mark = channel.position(); + } catch (IOException ex) { + ex.printStackTrace(); + mark = -1; + } + } + + @Override + public synchronized void reset() throws IOException { + if (mark < 0) { + throw new IOException("mark position not valid"); + } + channel.position(mark); + } +} \ No newline at end of file