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.StringWriter ; 33 import java.io.Reader ; 34 35 36 37 38 46 public class ReadStringStream 47 { 48 51 55 public static final int READ_TO_END_OF_STREAM = Integer.MAX_VALUE; 56 57 60 public static final int DEFAULT_BLOCK_READ_SIZE = 4096; 61 62 65 private Reader m_is; 66 private int m_maxSize; 67 private int m_bufferSize; 68 69 70 73 79 public ReadStringStream( Reader input ) 80 { 81 this( input, READ_TO_END_OF_STREAM, DEFAULT_BLOCK_READ_SIZE ); 82 } 83 84 85 89 public ReadStringStream( Reader input, int maxReadSize, int blockReadSize ) 90 { 91 setReader( input ); 92 setSizes( maxReadSize, blockReadSize ); 93 } 94 95 96 99 100 105 public void setReader( Reader input ) 106 { 107 if (input == null) 108 { 109 throw new IllegalArgumentException ( "Reader is null" ); 110 } 111 this.m_is = input; 112 } 113 114 115 118 public void setSizes( int maxReadSize, int blockReadSize ) 119 { 120 if (blockReadSize <= 0) 121 { 122 blockReadSize = DEFAULT_BLOCK_READ_SIZE; 123 } 124 if (maxReadSize <= 0 || maxReadSize > READ_TO_END_OF_STREAM) 125 { 126 maxReadSize = READ_TO_END_OF_STREAM; 127 } 128 if (maxReadSize < blockReadSize) 129 { 130 blockReadSize = maxReadSize; 131 } 132 this.m_maxSize = maxReadSize; 133 this.m_bufferSize = blockReadSize; 134 } 135 136 137 142 public String readStringStream() 143 throws IOException 144 { 145 return readStringStream( this.m_is, this.m_maxSize, this.m_bufferSize ); 146 } 147 148 149 157 public static String readStringStream( Reader input ) 158 throws IOException 159 { 160 return readStringStream( input, READ_TO_END_OF_STREAM, 161 DEFAULT_BLOCK_READ_SIZE ); 162 } 163 164 165 181 public static String readStringStream( Reader input, int maxReadSize, 182 int blockReadSize ) 183 throws IOException 184 { 185 StringWriter sw = new StringWriter (); 186 char buffer[] = new char[ blockReadSize ]; 187 int size = input.read( buffer, 0, blockReadSize ); 188 int totSize = size; 189 while (size > 0 && totSize < maxReadSize) 190 { 191 sw.write( buffer, 0, size ); 192 size = input.read( buffer, 0, blockReadSize ); 193 totSize += size; 194 } 195 sw.close(); 196 return sw.toString(); 197 } 198 } 199 200 | Popular Tags |