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