File - Quick Examples
In this tutorial we will look at several File snippets. These are related to performing several File utilities.
Android File Tutorial and Examples.
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.renderscript.ScriptGroup;
import com.jiangkang.tools.King;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
/**
* Created by jiangkang on 2017/9/20.
*/
public class FileUtils {
public static String getAssetsPath(String filename) {
return "file:///android_asset/" + filename;
}
public static InputStream getInputStreamFromAssets(String filename) throws IOException {
AssetManager manager = King.getApplicationContext().getAssets();
return manager.open(filename);
}
public static String[] listFilesFromPath(String path) throws IOException {
AssetManager manager = King.getApplicationContext().getAssets();
return manager.list(path);
}
public static AssetFileDescriptor getAssetFileDescription(String filename) throws IOException {
AssetManager manager = King.getApplicationContext().getAssets();
return manager.openFd(filename);
}
public static void writeStringToFile(String string, File file, boolean isAppending) {
FileWriter writer = null;
BufferedWriter bufferedWriter = null;
try {
writer = new FileWriter(file);
bufferedWriter = new BufferedWriter(writer);
if (isAppending) {
bufferedWriter.append(string);
} else {
bufferedWriter.write(string);
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeStringToFile(String string, String filePath, boolean isAppending) {
writeStringToFile(string, new File(filePath), isAppending);
}
public static Bitmap getBitmapFromAssets(String filename) throws IOException {
AssetManager manager = King.getApplicationContext().getAssets();
InputStream inputStream = manager.open(filename);
return BitmapFactory.decodeStream(inputStream);
}
public static void copyAssetsToFile(final String assetFilename, final String dstName) {
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
FileOutputStream fos = null;
try {
File dstFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ktools", dstName);
fos = new FileOutputStream(dstFile);
InputStream fileInputStream = getInputStreamFromAssets(assetFilename);
byte[] buffer = new byte[1024 * 2];
int byteCount;
while ((byteCount = fileInputStream.read(buffer)) != -1) {
fos.write(buffer, 0, byteCount);
}
fos.flush();
} catch (IOException e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
/**
* @param filename filename you will create
* @param directory directory where the file exists
* @return true if the file created successfully, or return false
*/
public static boolean createFile(String filename, String directory) {
boolean isSuccess = false;
File file = new File(directory, filename);
if (!file.exists()) {
try {
isSuccess = file.createNewFile();
} catch (IOException e) {
}
} else {
file.delete();
try {
isSuccess = file.createNewFile();
} catch (IOException e) {
}
}
return isSuccess;
}
public static boolean hideFile(String directory, String filename) {
boolean isSuccess;
File file = new File(directory, filename);
isSuccess = file.renameTo(new File(directory, ".".concat(filename)));
if (isSuccess) {
file.delete();
}
return isSuccess;
}
public static long getFolderSize(final String folderPath) {
long size = 0;
File directory = new File(folderPath);
if (directory.exists() && directory.isDirectory()) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
size += getFolderSize(file.getAbsolutePath());
} else {
size += file.length();
}
}
}
return size;
}
public static String readFromFile(String filename) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(getAssetFileDescription(filename).getFileDescriptor()));
StringBuilder stringBuilder = new StringBuilder();
String content;
while ((content = bufferedReader.readLine()) != null) {
stringBuilder.append(content);
}
return stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
1. Delete Directory and All its contents
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (String aChildren : children) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir != null && dir.delete();
}
2. Create Image File with Unique Name.
We can obtain the timestamp to get a unique name for our image. This method will create the image file in external storage and return the file.
@SuppressLint("SimpleDateFormat")
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
}
3. Get File Name.
We provide you the path name and expect you to get the file name. Obviously first you instantiate the java.io.File
, passing in the path name so as to create the File.
Then we check if it exists before invoking the getName()
method.
public static String getFilename(String pathName) {
File file = new File(pathName);
if(!file.exists()) {
return "";
}
return file.getName();
}
4. How to Save Byte Array to an Image file
We receive the byte array as parameter, save it as a file image and return the path.
// save jpg
private static String saveImage(byte[] bytes) {
Context context= MainApp.getInstance().getApplicationContext();
if (bytes == null) {
return "";
}
File dir = new File(FileAccessor.APP_ROOT_DIR, "image");
if (!dir.exists()) {
dir.mkdirs();
}
long t = new Date().getTime();
String filename = t + ".jpg";
String path = FileAccessor.Share_Image_Dir + "/" + filename;
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(path));
bos.write(bytes);
bos.flush();
bos.close();
//addImageToGallery(path, context);
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
5. How to save Bitmap as PNG file
public static void saveBitmapPng(final Bitmap bmp, final String filepath) {
new Thread() {
@Override
public void run() {
saveBitmapPngInner(bmp,filepath);
}
}.start();
}
private static void saveBitmapPngInner(Bitmap bmp,String filepath) {
if(bmp==null){
return;
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filepath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. How to Add Image to Gallery
private static void addImageToGallery(final String filePath,
final Context context,String contentType) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, contentType);
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
7. How to copy files in different thread
static void copyFilesInSeparateThread(final Context context, final List<File> filesToCopy) {
new Thread(new Runnable() {
@Override
public void run() {
List<File> copiedFiles = new ArrayList<>();
int i = 1;
for (File fileToCopy : filesToCopy) {
File dstDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getFolderName(context));
if (!dstDir.exists()) dstDir.mkdirs();
String[] filenameSplit = fileToCopy.getName().split(".");
String extension = "." + filenameSplit[filenameSplit.length - 1];
String filename = String.format("IMG_%s_%d.%s", new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()), i, extension);
File dstFile = new File(dstDir, filename);
try {
dstFile.createNewFile();
copyFile(fileToCopy, dstFile);
copiedFiles.add(dstFile);
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
scanCopiedImages(context, copiedFiles);
}
}).run();
}
static void scanCopiedImages(Context context, List<File> copiedImages) {
String[] paths = new String[copiedImages.size()];
for (int i = 0; i < copiedImages.size(); i++) {
paths[i] = copiedImages.get(i).toString();
}
MediaScannerConnection.scanFile(context,
paths, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d(getClass().getSimpleName(), "Scanned " + path + ":");
Log.d(getClass().getSimpleName(), "-> uri=" + uri);
}
});
}
8. How to copy a Stream
public static void copyStream(InputStream in, OutputStream out){
try {
int byteCount = 1024 * 1024;
byte[] buffer = new byte[byteCount];
int count = 0;
while ((count = in.read(buffer, 0, byteCount)) != -1){
out.write(buffer, 0, count);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
9. How to copy a File
This example makes use of the copyStream()
defined above.
public static void copyFile(File src, File dest) {
if (null == src || null == dest) {
return;
}
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
copyStream(in, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
10. How to Read Text File
You pass us the inputStream to that file and we read it and return result as a string.
public static String readTextFile(final InputStream stream) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final byte buf[] = new byte[1024];
int len;
try {
while ((len = stream.read(buf)) != -1) {
output.write(buf, 0, len);
}
output.close();
stream.close();
}
catch (final IOException ex) {
Logger.error(FileUtils.TAG, ex.getMessage(), ex);
}
return output.toString();
}
20+ Most Commonly Used Android File Utility Methods
As developers we are prone to mostly re-inventing the wheel in almost every project we involve ourselves in when other fabulous developers have already done the major work and shared them public for reusability. For example dealing with Files and directories is something that we do in almost every project we work in.
If you've been writing boilerplate code for handling files then you are in luck because you won't need anymore. There is this one class you can plug into your project or just copy the methods you need and go.
Let's look at some of these file utility methods this open source project provides us:
Let;s just say these are the imports to this one class:
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Comparator;
import okhttp3.ResponseBody;
Then here is the class definition:
Then these are the constants defined in the class:
public static final String DOCUMENTS_DIR = "documents";
// configured android:authorities in AndroidManifest (https://developer.android.com/reference/android/support/v4/content/FileProvider)
public static final String AUTHORITY = "YOUR_AUTHORITY.provider";
public static final String HIDDEN_PREFIX = ".";
Then the tags for sake of logging:
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
and create a private constructor:
OK, let's go:
1. How to Compare Files
We start with a file and folder comparator:
public static Comparator<File> sComparator = (f1, f2) -> {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
};
You are basically taking two file objects, getting their names, turning them to lowercase then comparing them.
2. How to Filter Files or Directorues
This filter only applies to Files and not directories. It will skip hidden files:
public static FileFilter sFileFilter = file -> {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
};
To filer directories/folders only:
public static FileFilter sDirFilter = file -> {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
};
3. How to get File extension from a String
For example for an image an extension may be ".png"
or jpeg
etc.
We want to return it including the dot:
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 "";
}
}
4. How to check if a Uri is a local one
That is if it is not pointing us to a web resource:
public static boolean isLocal(String url) {
return url != null && !url.startsWith("http://") && !url.startsWith("https://");
}
5. How to check if a Uri is a MediaStore one
6. How to Convert a File into a Uri
7. How to Return File Path without File Name
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;
}
8. How to Get MimeType of a given File or Uri
For a 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";
}
and for a Uri:
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
and for a String Uri:
public static String getMimeType(Context context, String url) {
String type = context.getContentResolver().getType(Uri.parse(url));
if (type == null) {
type = "application/octet-stream";
}
return type;
}
9. How to Check if Uri Authority is Local,ExternalStorage
For local:
public static boolean isLocalStorageDocument(Uri uri) {
return AUTHORITY.equals(uri.getAuthority());
}
for external storage:
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
and for downlaods:
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
and whether it's a media provider:
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
and whether it's google photos:
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
10. How to Get Data Column for a Uri
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.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = MediaStore.Files.FileColumns.DATA;
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} catch (Exception e) {
Timber.e(e);
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
11. How to Get a file path from a Uri
Fist you need to check if the path is local instead of assuming it is:
/**
*
* @param context The context.
* @param uri The Uri to query.
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
String absolutePath = getLocalPath(context, uri);
return absolutePath != null ? absolutePath : uri.toString();
}
private static String getLocalPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " 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];
} else if ("home".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/documents/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
// 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;
}
12. How to Convert a Uri into a File
Given a Uri, attempt to convert it into a File object and return the file otherwise null. Use the getPath()
defined earlier to obtain the path of the Uri.
/**
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
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;
}
13. How to render file size in human-readable format
If given the file size as an integer, and you need to render or display it in a human readable format for your users, then the following method will be important.
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
14. How to create an Intent for selecting items
The returned intent will be used with Intent.createChooser()
.
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
15. How to create a View intent for a given file
The aim is to create an Intent object to be used for opening or viewing some file. The file is passed as a parameter adn we need to determine it's type based on its extension.
/**
* @param file
* @return The intent for viewing file
*/
public static Intent getViewIntent(Context context, File file) {
//Uri uri = Uri.fromFile(file);
Uri uri = FileProvider.getUriForFile(context, AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = file.toString();
if (url.contains(".doc") || url.contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.contains(".ppt") || url.contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.contains(".xls") || url.contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.contains(".zip") || url.contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.contains(".wav") || url.contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.contains(".jpg") || url.contains(".jpeg") || url.contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.contains(".3gp") || url.contains(".mpg") || url.contains(".mpeg") ||
url.contains(".mpe") || url.contains(".mp4") || url.contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return intent;
}
16. How to get downloads Directory
Get it and return it as a File object:
public static File getDownloadsDir() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
17. How to get Cache directory
public static File getDocumentCacheDir(@NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
logDir(context.getCacheDir());
logDir(dir);
return dir;
}
18. How to get contents of a given directory
We get them then log the contained files' paths:
private static void logDir(File dir) {
if(!DEBUG) return;
Log.d(TAG, "Dir=" + dir);
File[] files = dir.listFiles();
for (File file : files) {
Log.d(TAG, "File=" + file.getPath());
}
}
19. How to Generate File Name
@Nullable
public static File generateFileName(@Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
logDir(directory);
return file;
}
20. How to write response body to Disk
The okhttp3.ResponseBody
to be written to disk is passed as a parameter:
/**
* @param body ResponseBody
* @param path file path
* @return File
*/
public static File writeResponseBodyToDisk(ResponseBody body, String path) {
try {
File target = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
inputStream = body.byteStream();
outputStream = new FileOutputStream(target);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
}
outputStream.flush();
return target;
} catch (IOException e) {
return null;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return null;
}
}
21. How to save file from Uri
The Uri is passed as a parameter as well as the destination path:
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
22. How to Read Bytes from File
You return a byte array when given a file path:
public static byte[] readBytesFromFile(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
23. How to Create Temporary Image File
public static File createTempImageFile(Context context, String fileName) throws IOException {
// Create an image file name
File storageDir = new File(context.getCacheDir(), DOCUMENTS_DIR);
return File.createTempFile(fileName, ".jpg", storageDir);
}
24. How to Get a File Name from a Uri
You are given a Uri and are asked to obtain the file name.
public static String getFileName(@NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null,
null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
Full Code
Here is the full class
package com.example.adhocdisplay;
/*
* Copyright (C) 2018 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Comparator;
import okhttp3.ResponseBody;
public class FileUtils {
public static final String DOCUMENTS_DIR = "documents";
// configured android:authorities in AndroidManifest (https://developer.android.com/reference/android/support/v4/content/FileProvider)
public static final String AUTHORITY = "YOUR_AUTHORITY.provider";
public static final String HIDDEN_PREFIX = ".";
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
/**
* File and folder comparator. TODO Expose sorting option method
*/
public static Comparator<File> sComparator = (f1, f2) -> {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
};
/**
* File (not directories) filter.
*/
public static FileFilter sFileFilter = file -> {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
};
/**
* Folder (directories) filter.
*/
public static FileFilter sDirFilter = file -> {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
};
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* 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) {
return url != null && !url.startsWith("http://") && !url.startsWith("https://");
}
/**
* @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) {
return (file != null) ? Uri.fromFile(file) : 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);
}
/**
* @return The MIME type for the give String Uri.
*/
public static String getMimeType(Context context, String url) {
String type = context.getContentResolver().getType(Uri.parse(url));
if (type == null) {
type = "application/octet-stream";
}
return type;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is local.
*/
public static boolean isLocalStorageDocument(Uri uri) {
return AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
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.
*/
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.
*/
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.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = MediaStore.Files.FileColumns.DATA;
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} catch (Exception e) {
Timber.e(e);
} 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)
*/
public static String getPath(final Context context, final Uri uri) {
String absolutePath = getLocalPath(context, uri);
return absolutePath != null ? absolutePath : uri.toString();
}
private static String getLocalPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " 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];
} else if ("home".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/documents/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
// 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.
* @author paulburke
* @see #getPath(Context, Uri)
*/
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;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
/**
* Creates View intent for given file
*
* @param file
* @return The intent for viewing file
*/
public static Intent getViewIntent(Context context, File file) {
//Uri uri = Uri.fromFile(file);
Uri uri = FileProvider.getUriForFile(context, AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = file.toString();
if (url.contains(".doc") || url.contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.contains(".ppt") || url.contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.contains(".xls") || url.contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.contains(".zip") || url.contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.contains(".wav") || url.contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.contains(".jpg") || url.contains(".jpeg") || url.contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.contains(".3gp") || url.contains(".mpg") || url.contains(".mpeg") ||
url.contains(".mpe") || url.contains(".mp4") || url.contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return intent;
}
public static File getDownloadsDir() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
public static File getDocumentCacheDir(@NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
logDir(context.getCacheDir());
logDir(dir);
return dir;
}
private static void logDir(File dir) {
if(!DEBUG) return;
Log.d(TAG, "Dir=" + dir);
File[] files = dir.listFiles();
for (File file : files) {
Log.d(TAG, "File=" + file.getPath());
}
}
@Nullable
public static File generateFileName(@Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
logDir(directory);
return file;
}
/**
* Writes response body to disk
*
* @param body ResponseBody
* @param path file path
* @return File
*/
public static File writeResponseBodyToDisk(ResponseBody body, String path) {
try {
File target = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
inputStream = body.byteStream();
outputStream = new FileOutputStream(target);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
}
outputStream.flush();
return target;
} catch (IOException e) {
return null;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return null;
}
}
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] readBytesFromFile(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
public static File createTempImageFile(Context context, String fileName) throws IOException {
// Create an image file name
File storageDir = new File(context.getCacheDir(), DOCUMENTS_DIR);
return File.createTempFile(fileName, ".jpg", storageDir);
}
public static String getFileName(@NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null,
null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf('/');
return filename.substring(index + 1);
}
}
Specia thanks to @coltoscosmin for creating and sharing this project.