Most of the times we need to work with Files in android. The concept here is File handling. We see how to handle and manipulate files in android.
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(); }
Oclemy
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:
Then here is the class definition:
Then these are the constants defined in the class:
Then the tags for sake of logging:
and create a private constructor:
OK, let’s go:
1. How to Compare Files
We start with a file and folder comparator:
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:
To filer directories/folders only:
3. How to get File extension from a String
For example for an image an extension may be
".png"
orjpeg
etc.We want to return it including the dot:
4. How to check if a Uri is a local one
That is if it is not pointing us to a web resource:
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
8. How to Get MimeType of a given File or Uri
For a file:
and for a Uri:
and for a String Uri:
9. How to Check if Uri Authority is Local,ExternalStorage
For local:
for external storage:
and for downlaods:
and whether it’s a media provider:
and whether it’s google photos:
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:
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:
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.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.
14. How to create an Intent for selecting items
The returned intent will be used with
Intent.createChooser()
.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.
16. How to get downloads Directory
Get it and return it as a File object:
17. How to get Cache directory
18. How to get contents of a given directory
We get them then log the contained files’ paths:
19. How to Generate File Name
20. How to write response body to Disk
The
okhttp3.ResponseBody
to be written to disk is passed as a parameter:21. How to save file from Uri
The Uri is passed as a parameter as well as the destination path:
22. How to Read Bytes from File
You return a byte array when given a file path:
23. How to Create Temporary Image File
24. How to Get a File Name from a Uri
You are given a Uri and are asked to obtain the file name.
Full Code
Here is the full class
Specia thanks to @coltoscosmin for creating and sharing this project.
Download Code