1 package org.columba.core.io; 2 3 import java.io.FilterInputStream ; 4 import java.io.IOException ; 5 import java.io.InputStream ; 6 7 public class SteerableInputStream extends FilterInputStream { 8 9 private long lengthLeft; 10 11 private long position; 12 13 public SteerableInputStream(InputStream in) { 14 super(in); 15 16 try { 17 lengthLeft = in.available(); 18 } catch (IOException e) { 19 lengthLeft = 0; 20 } 21 } 22 23 26 @Override 27 public int read() throws IOException { 28 if (lengthLeft > 0) { 29 int read = super.read(); 30 if (read != -1) { 31 lengthLeft--; 32 } 33 position++; 34 return read; 35 } 36 return -1; 37 } 38 39 42 @Override 43 public int read(byte[] b, int off, int len) throws IOException { 44 if (len > lengthLeft) { 45 int correctedLen = (int) lengthLeft; 46 int read = super.read(b, off, correctedLen); 47 lengthLeft -= read; 48 position += read; 49 return read; 50 } 51 int read = super.read(b, off, len); 52 lengthLeft -= read; 53 position += read; 54 return read; 55 56 } 57 58 61 public long getLengthLeft() { 62 return lengthLeft; 63 } 64 65 69 public void setLengthLeft(long lengthLeft) throws IOException { 70 this.lengthLeft = Math.min(lengthLeft, in.available()); 71 } 72 73 76 public long getPosition() { 77 return position; 78 } 79 80 84 public void setPosition(long newposition) throws IOException { 85 long skipped = in.skip(newposition - position); 86 lengthLeft = Math.max(0, lengthLeft - skipped); 87 position = newposition; 88 } 89 90 91 94 @Override 95 public int available() throws IOException { 96 return (int) lengthLeft; 97 } 98 99 100 103 @Override 104 public void close() throws IOException { 105 } 107 108 109 112 public void finalClose() throws IOException { 113 super.close(); 114 } 115 116 } 117 | Popular Tags |