01: package uk.org.ponder.streamutil;
02:
03: import java.io.InputStream;
04: import java.io.IOException;
05:
06: import uk.org.ponder.util.Logger;
07:
08: //import uk.org.ponder.byteutil.ByteWrap;
09:
10: /** RandomAccessInputStream abstracts a preexisting specified portion of a RandomAccessFile
11: * as an InputStream.
12: */
13:
14: public class RandomAccessInputStream extends InputStream {
15: private RandomAccessRead internalfile;
16: private long currentpos;
17: private long finalpos;
18:
19: public RandomAccessInputStream(RandomAccessRead internalfile)
20: throws IOException {
21: this (internalfile, 0, -1L);
22: }
23:
24: public RandomAccessInputStream(RandomAccessRead internalfile,
25: long initialpos) throws IOException {
26: this (internalfile, initialpos, -1L);
27: }
28:
29: public RandomAccessInputStream(RandomAccessRead internalfile,
30: long initialpos, long length) throws IOException {
31: this .internalfile = internalfile;
32: this .currentpos = initialpos;
33: this .finalpos = initialpos + length;
34: internalfile.seek(initialpos);
35: }
36:
37: /*
38: public RandomAccessFile getRandomAccessFile() {
39: return internalfile;
40: }
41: */
42: private StreamClosedCallback callback;
43:
44: public void setClosingCallback(StreamClosedCallback callback) {
45: this .callback = callback;
46: }
47:
48: public int read(byte[] array, int start, int length)
49: throws IOException {
50: if (currentpos >= finalpos)
51: return -1;
52: // if sufficiently near the end, truncate read request
53: if (finalpos != -1L && currentpos + length > finalpos)
54: length = (int) (finalpos - currentpos); // must be representable, since length is!
55:
56: int bytesread = internalfile.read(array, start, length);
57: // Logger.println("read: "+new ByteWrap(array, start, bytesread),
58: // Logger.DEBUG_INFORMATIONAL);
59: if (bytesread != -1)
60: currentpos += bytesread;
61: return bytesread;
62: }
63:
64: public int read() throws IOException {
65: int togo = -1;
66: if (finalpos != -1L && currentpos < finalpos) {
67: togo = internalfile.read();
68: ++currentpos;
69: }
70: return togo;
71: }
72:
73: /** Close this stream object. Note that this does NOT close the underlying
74: * random access file.
75: */
76: public void close() throws IOException {
77: if (callback != null) {
78: Logger.println("RandomAccessInputStream closing callback",
79: Logger.DEBUG_INFORMATIONAL);
80: callback.streamClosed(this );
81: callback = null;
82: }
83: internalfile = null;
84: currentpos = -1L;
85: }
86: }
|