| 1 | package be.nikiroo.utils.streams; |
| 2 | |
| 3 | import java.io.File; |
| 4 | import java.io.FileInputStream; |
| 5 | import java.io.FileNotFoundException; |
| 6 | import java.io.FilterInputStream; |
| 7 | import java.io.IOException; |
| 8 | import java.nio.channels.FileChannel; |
| 9 | |
| 10 | /** |
| 11 | * This is a markable (and thus reset-able) stream that you can create from a |
| 12 | * FileInputStream. |
| 13 | * |
| 14 | * @author niki |
| 15 | */ |
| 16 | public class MarkableFileInputStream extends FilterInputStream { |
| 17 | private FileChannel channel; |
| 18 | private long mark = 0; |
| 19 | |
| 20 | /** |
| 21 | * Create a new {@link MarkableFileInputStream} from this file. |
| 22 | * |
| 23 | * @param file |
| 24 | * the {@link File} to wrap |
| 25 | * |
| 26 | * @throws FileNotFoundException |
| 27 | * if the {@link File} cannot be found |
| 28 | */ |
| 29 | public MarkableFileInputStream(File file) throws FileNotFoundException { |
| 30 | this(new FileInputStream(file)); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Create a new {@link MarkableFileInputStream} from this stream. |
| 35 | * |
| 36 | * @param in |
| 37 | * the original {@link FileInputStream} to wrap |
| 38 | */ |
| 39 | public MarkableFileInputStream(FileInputStream in) { |
| 40 | super(in); |
| 41 | channel = in.getChannel(); |
| 42 | } |
| 43 | |
| 44 | @Override |
| 45 | public boolean markSupported() { |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | @Override |
| 50 | public synchronized void mark(int readlimit) { |
| 51 | try { |
| 52 | mark = channel.position(); |
| 53 | } catch (IOException ex) { |
| 54 | ex.printStackTrace(); |
| 55 | mark = -1; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public synchronized void reset() throws IOException { |
| 61 | if (mark < 0) { |
| 62 | throw new IOException("mark position not valid"); |
| 63 | } |
| 64 | channel.position(mark); |
| 65 | } |
| 66 | } |