| 1 16 package org.outerj.daisy.repository; 17 18 import java.io.InputStream ; 19 import java.io.IOException ; 20 21 public class PartHelper { 22 private static final int BUFFER_SIZE = 32768; 23 24 33 public static byte[] streamToByteArrayAndClose(InputStream is, int sizeHint) throws IOException { 34 if (is == null) 35 throw new IllegalArgumentException ("\"is\" param may not be null"); 36 37 try { 38 byte[] buffer = new byte[sizeHint != -1 ? sizeHint : BUFFER_SIZE]; 39 40 int read = is.read(buffer); 41 if (read == -1) { 42 return new byte[0]; 43 } else { 44 int c = is.read(); 45 if (c == -1) { 46 return read == buffer.length ? buffer : cutBuffer(buffer, read); 48 } else { 49 if (read == buffer.length) 51 buffer = growBuffer(buffer); 52 buffer[read] = (byte)c; 53 int pos = read + 1; 54 55 while (true) { 56 read = is.read(buffer, pos, buffer.length - pos); 57 if (read != -1) { 58 if (pos + read == buffer.length) { 59 c = is.read(); 61 if (c == -1) 62 return buffer; 63 buffer = growBuffer(buffer); 64 buffer[pos + read] = (byte)c; 65 pos = pos + read + 1; 66 } else { 67 pos = pos + read; 68 } 69 } else { 70 return cutBuffer(buffer, pos); 71 } 72 } 73 } 74 } 75 } finally { 76 is.close(); 77 } 78 } 79 80 private static byte[] growBuffer(byte[] buffer) { 81 byte[] newBuffer = new byte[buffer.length + BUFFER_SIZE]; 82 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); 83 return newBuffer; 84 } 85 86 private static byte[] cutBuffer(byte[] buffer, int length) { 87 byte[] newBuffer = new byte[length]; 88 System.arraycopy(buffer, 0, newBuffer, 0, length); 89 return newBuffer; 90 } 91 } 92 | Popular Tags |