1 26 27 28 package net.sourceforge.groboutils.util.io.v1; 29 30 import java.io.File ; 31 import java.io.IOException ; 32 import java.io.ByteArrayOutputStream ; 33 import java.io.InputStream ; 34 35 36 37 38 39 47 public class ReadByteStream 48 { 49 52 56 public static final int READ_TO_END_OF_STREAM = Integer.MAX_VALUE; 57 58 61 public static final int DEFAULT_BLOCK_READ_SIZE = 4096; 62 63 66 private InputStream m_is; 67 private int m_maxSize; 68 private int m_bufferSize; 69 70 71 74 77 public ReadByteStream( InputStream is ) 78 { 79 this( is, READ_TO_END_OF_STREAM, DEFAULT_BLOCK_READ_SIZE ); 80 } 81 82 83 86 public ReadByteStream( InputStream is, int maxReadSize, int blockReadSize ) 87 { 88 setInputStream( is ); 89 setSizes( maxReadSize, blockReadSize ); 90 } 91 92 93 96 97 100 public void setInputStream( InputStream is ) 101 { 102 if (is == null) 103 { 104 throw new IllegalArgumentException ( "input stream is null" ); 105 } 106 this.m_is = is; 107 } 108 109 110 113 public void setSizes( int maxReadSize, int blockReadSize ) 114 { 115 if (blockReadSize <= 0) 116 { 117 blockReadSize = DEFAULT_BLOCK_READ_SIZE; 118 } 119 if (maxReadSize <= 0 || maxReadSize > READ_TO_END_OF_STREAM) 120 { 121 maxReadSize = READ_TO_END_OF_STREAM; 122 } 123 if (maxReadSize < blockReadSize) 124 { 125 blockReadSize = maxReadSize; 126 } 127 this.m_maxSize = maxReadSize; 128 this.m_bufferSize = blockReadSize; 129 } 130 131 132 135 public byte[] readByteStream() 136 throws IOException 137 { 138 return readByteStream( this.m_is, this.m_maxSize, this.m_bufferSize ); 139 } 140 141 142 148 public static byte[] readByteStream( InputStream is ) 149 throws IOException 150 { 151 return readByteStream( is, READ_TO_END_OF_STREAM, 152 DEFAULT_BLOCK_READ_SIZE ); 153 } 154 155 156 172 public static byte[] readByteStream( InputStream is, int maxReadSize, 173 int blockReadSize ) 174 throws IOException 175 { 176 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 177 byte buffer[] = new byte[ blockReadSize ]; 178 int size = is.read( buffer, 0, blockReadSize ); 179 int totSize = size; 180 while (size > 0 && totSize < maxReadSize) 181 { 182 baos.write( buffer, 0, size ); 183 size = is.read( buffer, 0, blockReadSize ); 184 totSize += size; 185 } 186 baos.close(); 187 return baos.toByteArray(); 188 } 189 } 190 191 | Popular Tags |