1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.danube.webdav.fs;
14
15 import java.io.File;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.RandomAccessFile;
19
20
21
22
23
24
25
26 public class RandomAccessFileRangeInputStream extends InputStream {
27
28
29 protected RandomAccessFile raf;
30
31
32 protected long len;
33
34
35 protected long initialOffset;
36
37
38 protected long mark;
39
40
41 protected long markLen;
42
43
44
45
46
47
48
49
50 public RandomAccessFileRangeInputStream(File file, long from, long length) throws IOException {
51 raf = new RandomAccessFile(file, "r");
52 raf.skipBytes((int)from);
53 this.initialOffset = from;
54 this.len = length;
55 }
56
57 @Override
58 public int read() throws IOException {
59 if (len == 0) {
60 return -1;
61 } else {
62 len = len - 1;
63 return raf.read();
64 }
65 }
66
67 @Override
68 public int read(byte[] buf, int from, int length) throws IOException {
69 if (length > len) {
70 length = (int)len;
71 }
72 int r = raf.read(buf, from, length);
73 if (r >= 0) {
74 len = len - r;
75 }
76 return r;
77 }
78
79 @Override
80 public long skip(long l) throws IOException {
81 if (l > len) {
82 l = (int)len;
83 }
84 long s = raf.skipBytes((int)l);
85 if (s >= 0) {
86 len = len - s;
87 }
88 return s;
89 }
90
91 @Override
92 public void close() throws IOException {
93 raf.close();
94 }
95
96 @Override
97 public void mark(int i) {
98 try {
99 mark = raf.getFilePointer();
100 markLen = len;
101 } catch (IOException ignore) {
102 }
103 }
104
105 @Override
106 public void reset() throws IOException {
107 raf.seek(mark);
108 len = markLen;
109 }
110
111 @Override
112 public boolean markSupported() {
113 return true;
114 }
115 }