1 21 package org.apache.derby.client.am; 22 23 import java.io.InputStream ; 24 import java.io.IOException ; 25 import java.util.ArrayList ; 26 27 46 public class ByteArrayCombinerStream 47 extends InputStream { 48 49 50 private final ArrayList arrays; 51 52 private final long specifiedLength; 53 54 private long gOffset = 0; 55 56 private int arrayIndex = 0; 57 58 private byte[] curArray; 59 60 private int off = 0; 61 62 75 public ByteArrayCombinerStream(ArrayList arraysIn, long length) { 76 if (length < 0) { 78 throw new IllegalArgumentException ("Length cannot be negative: " + 79 length); 80 } 81 this.specifiedLength = length; 82 long tmpRemaining = length; 83 if (arraysIn != null && arraysIn.size() > 0) { 84 int arrayCount = arraysIn.size(); 86 byte[] tmpArray; 87 arrays = new ArrayList (arrayCount); 88 for (int i=0; i < arrayCount && tmpRemaining > 0; i++) { 91 tmpArray = (byte[])arraysIn.get(i); 92 if (tmpRemaining < tmpArray.length) { 93 byte[] shrunkArray = 95 new byte[(int)(tmpRemaining)]; 96 System.arraycopy(tmpArray, 0, 97 shrunkArray, 0, shrunkArray.length); 98 arrays.add(shrunkArray); 99 tmpRemaining -= shrunkArray.length; 100 break; 101 } else { 102 tmpRemaining -= tmpArray.length; 104 arrays.add(tmpArray); 105 } 106 } 107 curArray = nextArray(); 109 } else { 110 gOffset = length; 112 arrays = null; 113 } 114 if (tmpRemaining > 0) { 116 throw new IllegalArgumentException ("Not enough data, " + 117 tmpRemaining + " bytes short of specified length " + 118 length); 119 } 120 } 121 122 127 public int read() 128 throws IOException { 129 if (curArray == null) { 130 return -1; 131 } 132 if (off >= curArray.length) { 133 curArray = nextArray(); 134 if (curArray == null) { 135 return -1; 136 } 137 } 138 gOffset++; 139 return curArray[off++]; 140 } 141 142 155 public int read(byte[] buf, int offset, int length) 156 throws IOException { 157 int read = 0; 158 if (curArray == null) { 159 return -1; 160 } 161 if (length <= (curArray.length - off)) { 162 System.arraycopy(curArray, off, buf, offset, length); 163 off += length; 164 gOffset += length; 165 read = length; 166 } else { 167 int toRead = 0; 168 while (curArray != null && read < length) { 169 toRead = Math.min(curArray.length - off, length - read); 170 System.arraycopy(curArray, off, buf, offset + read, toRead); 171 read += toRead; 172 gOffset += toRead; 173 off += toRead; 174 if ( off < curArray.length) { 175 break; 176 } 177 curArray = nextArray(); 178 } 179 } 180 return read; 181 } 182 183 189 public int available() { 190 return (int)(specifiedLength - gOffset); 191 } 192 193 201 private byte[] nextArray() { 202 if (arrayIndex >= arrays.size()) { 203 return null; 204 } 205 byte[] tmp = (byte[])arrays.get(arrayIndex); 206 arrays.set(arrayIndex++, null); 207 off = 0; 208 return tmp; 209 } 210 } | Popular Tags |