1 23 package org.archive.io; 24 25 26 import java.io.File ; 27 import java.io.IOException ; 28 import java.io.RandomAccessFile ; 29 30 31 36 public class RandomAccessInputStream extends SeekInputStream { 37 38 41 private RandomAccessFile raf = null; 42 43 47 private long markpos = -1; 48 49 53 private boolean sympathyClose; 54 55 65 public RandomAccessInputStream(RandomAccessFile raf) 66 throws IOException { 67 this(raf, false, 0); 68 } 69 70 77 public RandomAccessInputStream(final File file) 78 throws IOException { 79 this(new RandomAccessFile (file, "r"), true, 0); 80 } 81 82 90 public RandomAccessInputStream(final File file, final long offset) 91 throws IOException { 92 this(new RandomAccessFile (file, "r"), true, offset); 93 } 94 95 102 public RandomAccessInputStream(final RandomAccessFile raf, 103 final boolean sympathyClose, final long offset) 104 throws IOException { 105 super(); 106 this.sympathyClose = sympathyClose; 107 this.raf = raf; 108 if (offset > 0) { 109 this.raf.seek(offset); 110 } 111 } 112 113 116 public int read() throws IOException { 117 return this.raf.read(); 118 } 119 120 123 public int read(byte[] b, int off, int len) throws IOException { 124 return this.raf.read(b, off, len); 125 } 126 127 130 public int read(byte[] b) throws IOException { 131 return this.raf.read(b); 132 } 133 134 137 public long skip(long n) throws IOException { 138 this.raf.seek(this.raf.getFilePointer() + n); 139 return n; 140 } 141 142 public long position() throws IOException { 143 return this.raf.getFilePointer(); 144 } 145 146 public void position(long position) throws IOException { 147 this.raf.seek(position); 148 } 149 150 public int available() throws IOException { 151 long amount = this.raf.length() - this.position(); 152 return (amount >= Integer.MAX_VALUE)? Integer.MAX_VALUE: (int)amount; 153 } 154 155 public boolean markSupported() { 156 return true; 157 } 158 159 public synchronized void mark(int readlimit) { 160 try { 161 this.markpos = position(); 162 } catch (IOException e) { 163 this.markpos = -1; 165 } 166 } 167 168 public synchronized void reset() throws IOException { 169 if (this.markpos == -1) { 170 throw new IOException ("Mark has not been set."); 171 } 172 position(this.markpos); 173 } 174 175 public void close() throws IOException { 176 try { 177 super.close(); 178 } finally { 179 if (this.sympathyClose) { 180 this.raf.close(); 181 } 182 } 183 } 184 } | Popular Tags |