Snippets

Muhammed Ballan FileUtils contains many file operations that gonna be useful in any application may need to deal with files

Created by Muhammed Ballan
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * Created by mballan on 22.08.2015.
 Many file operations are done here
 */
public class FileUtils {

	private String PATH_OF_LOCAL_IMAGES; // filled in the Constructor with the SdCard and Sounds file
	private String IMAGES_FOLDER_NAME = "Images/";
	public static final String MIME_TYPE_AUDIO = "audio/*";
	public static final String MIME_TYPE_TEXT = "text/*";
	public static final String MIME_TYPE_IMAGE = "image/*";
	public static final String MIME_TYPE_VIDEO = "video/*";
	public static final String MIME_TYPE_APP = "application/*";

	public static final String HIDDEN_PREFIX = ".";

	private static FileUtils instance = null;
	private FileUtils() {
		PATH_OF_LOCAL_IMAGES = Environment.getExternalStorageDirectory().getPath() + "/" + IMAGES_FOLDER_NAME;
		createDirIfNoExists();
	}

	public static FileUtils getInstance() {
		if( instance == null) {
			instance = new FileUtils();
		}
		return instance;
	}

	private void createDirIfNoExists() {
		File folder = new File(PATH_OF_LOCAL_IMAGES);
		if (!folder.exists()) {
			folder.mkdir();
		}
	}

	public boolean saveBitmapToFile(Bitmap bitmap, String fileName) {
		FileOutputStream out = null;
		boolean returnValue = false;
		try {
			out = new FileOutputStream(PATH_OF_LOCAL_IMAGES+fileName);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
			// PNG is a lossless format, the compression factor (100) is ignored
			returnValue = true;
		} catch (Exception e) {
			returnValue = false;
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnValue;
	}

	public File getOutputImagefile() {
		// Location on external storage, Guid for unique name
		return new File(PATH_OF_LOCAL_IMAGES +getGUID()+".jpg");
	}

	public File saveBitmapToFile(File file){
		File fileToReturn = null;
		FileOutputStream outputStream = null;
		try {

			//File file = new File(uri.getPath());

			// BitmapFactory options to downsize the image
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			o.inSampleSize = 10; // Image resulotion
			// factor of downsizing the image

			FileInputStream inputStream = new FileInputStream(file);
			//Bitmap selectedBitmap = null;
			BitmapFactory.decodeStream(inputStream, null, o);
			inputStream.close();

			// The new size we want to scale to
			final int REQUIRED_SIZE=100;

			// Find the correct scale value. It should be the power of 2.
			int scale = 1;
			while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
							o.outHeight / scale / 2 >= REQUIRED_SIZE) {
				scale *= 2;
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			inputStream = new FileInputStream(file);

			Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
			inputStream.close();


			file.createNewFile();
			outputStream = new FileOutputStream(file);

			selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100 , outputStream);

			fileToReturn = file;
			//outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			Utils.LogError("FILE: " + e.getLocalizedMessage());
		} finally {
			//close input
			if (outputStream != null) {
				try {
					outputStream.close();
				}
				catch(IOException ioex) {
					//Very bad things just happened... handle it
				}
			}
		}
		return fileToReturn;
	}

	public File saveBitmapToFileWithGUID(Bitmap bitmap) {
		FileOutputStream out = null;
		File returnValue = null;
		try {
			String path = PATH_OF_LOCAL_IMAGES+getGUID()+".jpg";
			out = new FileOutputStream(path);

			bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out); // bmp is your Bitmap instance
			// PNG is a lossless format, the compression factor (100) is ignored
			// Open file if exists
			File file = new File(path);
			if(file.exists())
				returnValue = file;
			else returnValue = null;

		} catch (Exception e) {
			returnValue = null;
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnValue;
	}


	public static void copy(File src, File dst) throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dst);

			// Transfer bytes from in to out
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

		} catch (IOException e) {
			throw e;
		} finally {
			try {
			if(in!=null)in.close();
			if(out!=null)out.close();} catch (IOException e){ throw e;}
		}
	}


	public String getRealPathFromURI(Context context, Uri contentURI) {
		String result;
		Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
		if (cursor == null) { // Source is Dropbox or other similar local file path
			result = contentURI.getPath();
		} else {
			cursor.moveToFirst();
			int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
			result = cursor.getString(idx);
			cursor.close();
		}
		return result;
	}

	public String getGUID() {
		String guid = UUID.randomUUID().toString();
		return guid;
	}

	/**
	 * Gets the extension of a file name, like ".png" or ".jpg".
	 *
	 * @param uri
	 * @return Extension including the dot("."); "" if there is no extension;
	 *         null if uri was null.
	 */
	public static String getExtension(String uri) {
		if (uri == null) {
			return null;
		}

		int dot = uri.lastIndexOf(".");
		if (dot >= 0) {
			return uri.substring(dot);
		} else {
			// No extension.
			return "";
		}
	}

	/**
	 * @return Whether the URI is a local one.
	 */
	public static boolean isLocal(String url) {
		if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
			return true;
		}
		return false;
	}

	/**
	 * @return True if Uri is a MediaStore Uri.
	 * @author paulburke
	 */
	public static boolean isMediaUri(Uri uri) {
		return "media".equalsIgnoreCase(uri.getAuthority());
	}

	/**
	 * Convert File into Uri.
	 *
	 * @param file
	 * @return uri
	 */
	public static Uri getUri(File file) {
		if (file != null) {
			return Uri.fromFile(file);
		}
		return null;
	}

	/**
	 * Returns the path only (without file name).
	 *
	 * @param file
	 * @return
	 */
	public static File getPathWithoutFilename(File file) {
		if (file != null) {
			if (file.isDirectory()) {
				// no file to be split off. Return everything
				return file;
			} else {
				String filename = file.getName();
				String filepath = file.getAbsolutePath();

				// Construct path without file name.
				String pathwithoutname = filepath.substring(0,
								filepath.length() - filename.length());
				if (pathwithoutname.endsWith("/")) {
					pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
				}
				return new File(pathwithoutname);
			}
		}
		return null;
	}

	/**
	 * @return The MIME type for the given file.
	 */
	public static String getMimeType(File file) {

		String extension = getExtension(file.getName());

		if (extension.length() > 0)
			return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));

		return "application/octet-stream";
	}

	/**
	 * @return The MIME type for the give Uri.
	 */
	public static String getMimeType(Context context, Uri uri) {
		File file = new File(getPath(context, uri));
		return getMimeType(file);
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is {@link LocalStorageProvider}.
	 * @author paulburke
	 */
	public static boolean isLocalStorageDocument(Uri uri) {
		return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
	}

	/**
	 * Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
	 * should not be called on the UI thread.
	 *
	 * @param context
	 * @param uri
	 * @return
	 * @author paulburke
	 */
	public static Bitmap getThumbnail(Context context, Uri uri) {
		return getThumbnail(context, uri, getMimeType(context, uri));
	}

	/**
	 * Attempt to retrieve the thumbnail of given File from the MediaStore. This
	 * should not be called on the UI thread.
	 *
	 * @param context
	 * @param file
	 * @return
	 * @author paulburke
	 */
	public static Bitmap getThumbnail(Context context, File file) {
		return getThumbnail(context, getUri(file), getMimeType(file));
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 * @author paulburke
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 * @author paulburke
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 * @author paulburke
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 * @author paulburke
	 */
	public static String getDataColumn(Context context, Uri uri, String selection,
	                                   String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = {
						column
		};

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
							null);
			if (cursor != null && cursor.moveToFirst()) {

				// TODO: Remove this when release
				DatabaseUtils.dumpCursor(cursor);

				final int column_index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(column_index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * Get a file path from a Uri. This will get the the path for Storage Access
	 * Framework Documents, as well as the _data field for the MediaStore and
	 * other file-based ContentProviders.<br>
	 * <br>
	 * Callers should check whether the path is local before assuming it
	 * represents a local file.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @see #isLocal(String)
	 * @see #getFile(Context, Uri)
	 * @author paulburke
	 */
	@SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {


			Utils.LogDebug(" File - "+
							"Authority: " + uri.getAuthority() +
											", Fragment: " + uri.getFragment() +
											", Port: " + uri.getPort() +
											", Query: " + uri.getQuery() +
											", Scheme: " + uri.getScheme() +
											", Host: " + uri.getHost() +
											", Segments: " + uri.getPathSegments().toString()
			);

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// LocalStorageProvider
			if (isLocalStorageDocument(uri)) {
				// The path is the id
				return DocumentsContract.getDocumentId(uri);
			}
			// ExternalStorageProvider
			else if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
								Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] {
								split[1]
				};

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	/**
	 * Convert Uri into File, if possible.
	 *
	 * @return file A local file that the Uri was pointing to, or null if the
	 *         Uri is unsupported or pointed to a remote resource.
	 * @see #getPath(Context, Uri)
	 * @author paulburke
	 */
	public static File getFile(Context context, Uri uri) {
		if (uri != null) {
			String path = getPath(context, uri);
			if (path != null && isLocal(path)) {
				return new File(path);
			}
		}
		return null;
	}

	/**
	 * Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
	 * should not be called on the UI thread.
	 *
	 * @param context
	 * @param uri
	 * @param mimeType
	 * @return
	 * @author paulburke
	 */
	public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
			Utils.LogError("Attempting to get thumbnail");

		if (!isMediaUri(uri)) {
			Utils.LogError("You can only retrieve thumbnails for images and videos.");
			return null;
		}

		Bitmap bm = null;
		if (uri != null) {
			final ContentResolver resolver = context.getContentResolver();
			Cursor cursor = null;
			try {
				cursor = resolver.query(uri, null, null, null, null);
				if (cursor.moveToFirst()) {
					final int id = cursor.getInt(0);
						Utils.LogError("Got thumb ID: " + id);

					if (mimeType.contains("video")) {
						bm = MediaStore.Video.Thumbnails.getThumbnail(
										resolver,
										id,
										MediaStore.Video.Thumbnails.MINI_KIND,
										null);
					}
					else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
						bm = MediaStore.Images.Thumbnails.getThumbnail(
										resolver,
										id,
										MediaStore.Images.Thumbnails.MINI_KIND,
										null);
					}
				}
			} catch (Exception e) {
					Utils.LogError("getThumbnail"+ e.getLocalizedMessage());
			} finally {
				if (cursor != null)
					cursor.close();
			}
		}
		return bm;
	}
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.