@@ -197,50 +197,89 @@ public static long fileSizeFromUri( Uri uri, Context ctx) {
197
197
}
198
198
199
199
public static byte [] readBytesFromInputStream (InputStream is , final int size ) {
200
+ if ( size <= 0 ) {
201
+ return null ;
202
+ }
203
+
200
204
byte [] bytes = null ;
201
205
try {
202
- bytes = new byte [size ];
206
+ bytes = newBytes (size );
207
+ if ( bytes == null ) {
208
+ return null ;
209
+ }
203
210
int remain = size ;
204
211
int offset = 0 ;
205
212
while ( remain > 0 ) {
206
213
int read = is .read ( bytes , offset , remain );
207
214
remain -= read ;
208
215
offset += read ;
209
216
}
210
- } catch ( Exception e ){
217
+ } catch ( Exception e ) {
211
218
bytes = null ;
219
+ Log .e ( TAG , "readBytesFromInputStream Exception" );
220
+ e .printStackTrace ();
212
221
}
213
222
return bytes ;
214
223
}
215
224
216
225
public static byte [] readBytesFromFile ( File file ) {
217
226
byte [] bytes = null ;
218
227
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
+ }
219
233
FileInputStream is = new FileInputStream ( file );
220
- int size = (int ) file .length ();
221
- bytes = readBytesFromInputStream (is , size );
234
+ bytes = readBytesFromInputStream (is , (int ) size );
222
235
is .close ();
223
236
} catch ( Exception e ){
224
237
bytes = null ;
238
+ Log .e ( TAG , "readBytesFromFile Exception" );
239
+ e .printStackTrace ();
225
240
}
226
241
return bytes ;
227
242
}
228
243
229
244
public static byte [] readBytesFromUri ( Uri uri , Context ctx ) {
230
245
byte [] bytes = null ;
231
246
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
+ }
232
252
InputStream is = ctx .getContentResolver ().openInputStream ( uri );
233
253
if ( is != null ) {
234
- int size = (int ) fileSizeFromUri ( uri , ctx );
235
- bytes = readBytesFromInputStream ( is , size );
254
+ bytes = readBytesFromInputStream ( is , (int ) size );
236
255
is .close ();
237
256
}
238
257
} catch ( Exception e ){
239
258
bytes = null ;
259
+ Log .e ( TAG , "readBytesFromFile Exception" );
260
+ e .printStackTrace ();
240
261
}
241
262
return bytes ;
242
263
}
243
264
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
+ }
244
283
245
284
public static boolean stringBuilderAddStream ( StringBuilder sb , InputStream is ) {
246
285
boolean ok = true ;
0 commit comments