1 31 32 package org.apache.commons.httpclient; 33 34 import java.io.FilterInputStream ; 35 import java.io.IOException ; 36 import java.io.InputStream ; 37 38 46 47 public class ContentLengthInputStream extends FilterInputStream { 48 49 53 private int contentLength; 54 55 56 private int pos = 0; 57 58 59 private boolean closed = false; 60 61 68 public ContentLengthInputStream(InputStream in, int contentLength) { 69 super(in); 70 this.contentLength = contentLength; 71 } 72 73 80 public void close() throws IOException { 81 if (!closed) { 82 try { 83 ChunkedInputStream.exhaustInputStream(this); 84 } finally { 85 closed = true; 88 } 89 } 90 } 91 92 93 99 public int read() throws IOException { 100 if (closed) { 101 throw new IOException ("Attempted read from closed stream."); 102 } 103 104 if (pos >= contentLength) { 105 return -1; 106 } 107 pos++; 108 return super.read(); 109 } 110 111 123 public int read (byte[] b, int off, int len) throws java.io.IOException { 124 if (closed) { 125 throw new IOException ("Attempted read from closed stream."); 126 } 127 128 if (pos >= contentLength) { 129 return -1; 130 } 131 132 if (pos + len > contentLength) { 133 len = contentLength - pos; 134 } 135 int count = super.read(b, off, len); 136 pos += count; 137 return count; 138 } 139 140 141 148 public int read(byte[] b) throws IOException { 149 return read(b, 0, b.length); 150 } 151 152 } 153 | Popular Tags |