1 5 package com.oreilly.servlet.multipart; 6 7 import java.io.IOException ; 8 9 import javax.servlet.ServletInputStream ; 10 11 32 public class BufferedServletInputStream extends ServletInputStream { 33 34 35 private ServletInputStream in; 36 37 38 private byte[] buf = new byte[64*1024]; 40 41 private int count; 42 43 44 private int pos; 45 46 52 public BufferedServletInputStream(ServletInputStream in) { 53 this.in = in; 54 } 55 56 63 private void fill() throws IOException { 64 int i = in.read(buf, 0, buf.length); 65 if (i > 0) { 66 pos = 0; 67 count = i; 68 } 69 } 70 71 84 public int readLine(byte b[], int off, int len) throws IOException { 85 int total = 0; 86 if (len == 0) { 87 return 0; 88 } 89 90 int avail = count - pos; 91 if (avail <= 0) { 92 fill(); 93 avail = count - pos; 94 if (avail <= 0) { 95 return -1; 96 } 97 } 98 int copy = Math.min(len, avail); 99 int eol = findeol(buf, pos, copy); 100 if (eol != -1) { 101 copy = eol; 102 } 103 System.arraycopy(buf, pos, b, off, copy); 104 pos += copy; 105 total += copy; 106 107 while (total < len && eol == -1) { 108 fill(); 109 avail = count - pos; 110 if(avail <= 0) { 111 return total; 112 } 113 copy = Math.min(len - total, avail); 114 eol = findeol(buf, pos, copy); 115 if (eol != -1) { 116 copy = eol; 117 } 118 System.arraycopy(buf, pos, b, off + total, copy); 119 pos += copy; 120 total += copy; 121 } 122 return total; 123 } 124 125 135 private static int findeol(byte b[], int pos, int len) { 136 int end = pos + len; 137 int i = pos; 138 while (i < end) { 139 if (b[i++] == '\n') { 140 return i - pos; 141 } 142 } 143 return -1; 144 } 145 146 154 public int read() throws IOException { 155 if (count <= pos) { 156 fill(); 157 if (count <= pos) { 158 return -1; 159 } 160 } 161 return buf[pos++] & 0xff; 162 } 163 164 176 public int read(byte b[], int off, int len) throws IOException 177 { 178 int total = 0; 179 while (total < len) { 180 int avail = count - pos; 181 if (avail <= 0) { 182 fill(); 183 avail = count - pos; 184 if(avail <= 0) { 185 if (total > 0) 186 return total; 187 else 188 return -1; 189 } 190 } 191 int copy = Math.min(len - total, avail); 192 System.arraycopy(buf, pos, b, off + total, copy); 193 pos += copy; 194 total += copy; 195 } 196 return total; 197 } 198 } 199 | Popular Tags |