@@ -196,18 +196,50 @@ public static long fileSizeFromUri( Uri uri, Context ctx) {
196
196
return -1 ;
197
197
}
198
198
199
- public static byte [] readBytesFromInputStream (InputStream is , final int size ) {
199
+ public static String runtimeMemory () {
200
+ Runtime runtime = Runtime .getRuntime ();
201
+ long totalMemory = runtime .totalMemory ();
202
+ long maxMemory = runtime .maxMemory ();
203
+ long freeMemory = runtime .freeMemory ();
204
+ return "memory: total" + totalMemory + "; max " + maxMemory + "; free " + freeMemory ;
205
+ }
206
+
207
+ public static byte [] newBytes (final int size ) {
208
+ Log .d ( TAG , "newBytes(" + size + ") " + runtimeMemory ());
209
+ if ( size <= 0 ) {
210
+ return null ;
211
+ }
212
+
200
213
byte [] bytes = null ;
201
214
try {
202
215
bytes = new byte [size ];
216
+ } catch ( Exception e ) {
217
+ bytes = null ;
218
+ } catch ( OutOfMemoryError oom ) {
219
+ bytes = null ;
220
+ }
221
+ return bytes ;
222
+ }
223
+
224
+ public static byte [] readBytesFromInputStream (InputStream is , final int size ) {
225
+ if ( size <= 0 ) {
226
+ return null ;
227
+ }
228
+
229
+ byte [] bytes = null ;
230
+ try {
231
+ bytes = newBytes (size );
232
+ if ( bytes == null ) {
233
+ return null ;
234
+ }
203
235
int remain = size ;
204
236
int offset = 0 ;
205
237
while ( remain > 0 ) {
206
238
int read = is .read ( bytes , offset , remain );
207
239
remain -= read ;
208
240
offset += read ;
209
241
}
210
- } catch ( Exception e ){
242
+ } catch ( Exception e ) {
211
243
bytes = null ;
212
244
}
213
245
return bytes ;
@@ -216,8 +248,11 @@ public static byte[] readBytesFromInputStream(InputStream is, final int size) {
216
248
public static byte [] readBytesFromFile ( File file ) {
217
249
byte [] bytes = null ;
218
250
try {
219
- FileInputStream is = new FileInputStream ( file );
220
251
int size = (int ) file .length ();
252
+ if ( size <= 0 ) {
253
+ return null ;
254
+ }
255
+ FileInputStream is = new FileInputStream ( file );
221
256
bytes = readBytesFromInputStream (is , size );
222
257
is .close ();
223
258
} catch ( Exception e ){
@@ -229,9 +264,12 @@ public static byte[] readBytesFromFile( File file) {
229
264
public static byte [] readBytesFromUri ( Uri uri , Context ctx ) {
230
265
byte [] bytes = null ;
231
266
try {
267
+ int size = (int ) fileSizeFromUri ( uri , ctx );
268
+ if ( size <= 0 ) {
269
+ return null ;
270
+ }
232
271
InputStream is = ctx .getContentResolver ().openInputStream ( uri );
233
272
if ( is != null ) {
234
- int size = (int ) fileSizeFromUri ( uri , ctx );
235
273
bytes = readBytesFromInputStream ( is , size );
236
274
is .close ();
237
275
}
@@ -241,7 +279,6 @@ public static byte[] readBytesFromUri( Uri uri, Context ctx) {
241
279
return bytes ;
242
280
}
243
281
244
-
245
282
public static boolean stringBuilderAddStream ( StringBuilder sb , InputStream is ) {
246
283
boolean ok = true ;
247
284
try {
0 commit comments