@@ -197,50 +197,89 @@ public static long fileSizeFromUri( Uri uri, Context ctx) {
197197 }
198198
199199 public static byte [] readBytesFromInputStream (InputStream is , final int size ) {
200+ if ( size <= 0 ) {
201+ return null ;
202+ }
203+
200204 byte [] bytes = null ;
201205 try {
202- bytes = new byte [size ];
206+ bytes = newBytes (size );
207+ if ( bytes == null ) {
208+ return null ;
209+ }
203210 int remain = size ;
204211 int offset = 0 ;
205212 while ( remain > 0 ) {
206213 int read = is .read ( bytes , offset , remain );
207214 remain -= read ;
208215 offset += read ;
209216 }
210- } catch ( Exception e ){
217+ } catch ( Exception e ) {
211218 bytes = null ;
219+ Log .e ( TAG , "readBytesFromInputStream Exception" );
220+ e .printStackTrace ();
212221 }
213222 return bytes ;
214223 }
215224
216225 public static byte [] readBytesFromFile ( File file ) {
217226 byte [] bytes = null ;
218227 try {
228+ long size = file .length ();
229+ if ( size <= 0 || size > Integer .MAX_VALUE ) {
230+ Log .e ( TAG , "readBytesFromFile error - size" );
231+ return null ;
232+ }
219233 FileInputStream is = new FileInputStream ( file );
220- int size = (int ) file .length ();
221- bytes = readBytesFromInputStream (is , size );
234+ bytes = readBytesFromInputStream (is , (int ) size );
222235 is .close ();
223236 } catch ( Exception e ){
224237 bytes = null ;
238+ Log .e ( TAG , "readBytesFromFile Exception" );
239+ e .printStackTrace ();
225240 }
226241 return bytes ;
227242 }
228243
229244 public static byte [] readBytesFromUri ( Uri uri , Context ctx ) {
230245 byte [] bytes = null ;
231246 try {
247+ long size = fileSizeFromUri ( uri , ctx );
248+ if ( size <= 0 || size > Integer .MAX_VALUE ) {
249+ Log .e ( TAG , "readBytesFromUri error - size" );
250+ return null ;
251+ }
232252 InputStream is = ctx .getContentResolver ().openInputStream ( uri );
233253 if ( is != null ) {
234- int size = (int ) fileSizeFromUri ( uri , ctx );
235- bytes = readBytesFromInputStream ( is , size );
254+ bytes = readBytesFromInputStream ( is , (int ) size );
236255 is .close ();
237256 }
238257 } catch ( Exception e ){
239258 bytes = null ;
259+ Log .e ( TAG , "readBytesFromFile Exception" );
260+ e .printStackTrace ();
240261 }
241262 return bytes ;
242263 }
243264
265+ public static byte [] newBytes (final int size ) {
266+ if ( size <= 0 ) {
267+ return null ;
268+ }
269+
270+ byte [] bytes = null ;
271+ try {
272+ bytes = new byte [size ];
273+ } catch ( Exception e ) {
274+ bytes = null ;
275+ Log .e ( TAG , "newBytes(" + size + ") Exception" );
276+ e .printStackTrace ();
277+ } catch ( OutOfMemoryError oom ) {
278+ bytes = null ;
279+ Log .e ( TAG , "newBytes(" + size + ") OutOfMemoryError" );
280+ }
281+ return bytes ;
282+ }
244283
245284 public static boolean stringBuilderAddStream ( StringBuilder sb , InputStream is ) {
246285 boolean ok = true ;
0 commit comments