Last active
November 30, 2018 11:31
-
-
Save AlonsoFloo/b4455a2e275d561c02facbdd9002bd3d to your computer and use it in GitHub Desktop.
Android File handling utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<application> | |
<provider | |
android:name="android.support.v4.content.FileProvider" | |
android:authorities="${applicationId}.fileprovider" | |
android:exported="false" | |
android:grantUriPermissions="true"> | |
<meta-data | |
android:name="android.support.FILE_PROVIDER_PATHS" | |
android:resource="@xml/file_paths" /> | |
</provider> | |
</application> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<paths> | |
<files-path name="my_docs" path="."/> | |
<cache-path name="my_cache" path="."/> | |
<external-path name="my_picture_temporary" path="." /> | |
</paths> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* <h1>FileUtil</h1> | |
* Utility class to handle disk file | |
* <p> | |
* | |
* @author Florian ALONSO | |
* @version 2.0 | |
* @see Context | |
* @see File | |
* @since 2.0 | |
*/ | |
public abstract class FileUtil { | |
/** | |
* <h1>FileSaveAsynchronousCallback</h1> | |
* Utility class to handle disk file callback | |
* <p> | |
* | |
* @author Florian ALONSO (Neopixl) | |
* @version 2.0 | |
* @see File | |
* @since 2.0 | |
*/ | |
public interface FileSaveAsynchronousCallback { | |
void finish(File file); | |
} | |
/** | |
* Return a file from the application file directory | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @param fileName the filename | |
* @return the file | |
* @since 2.0 | |
*/ | |
public static File getCacheFile(Context context, String directoryName, String fileName) { | |
File directory = new File(context.getCacheDir(), directoryName); | |
return new File(directory, fileName); | |
} | |
/** | |
* Return a file from the application file directory | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @param fileName the filename | |
* @return the file | |
* @since 2.0 | |
*/ | |
public static File getDataFile(Context context, String directoryName, String fileName) { | |
File directory = new File(context.getFilesDir(), directoryName); | |
return new File(directory, fileName); | |
} | |
/** | |
* Return the cache directory | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @return the file | |
* @since 2.0 | |
*/ | |
public static File getCacheDir(Context context, String directoryName) { | |
return new File(context.getCacheDir(), directoryName); | |
} | |
/** | |
* Return the file directory | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @return the file | |
* @since 2.0 | |
*/ | |
public static File getDataDir(Context context, String directoryName) { | |
return new File(context.getFilesDir(), directoryName); | |
} | |
/** | |
* Save an file in a specified file *ASYNCHRONOUS* | |
* | |
* @param context the context of the application | |
* @param fileBytes the byte to save | |
* @param outFile the file to write in | |
* @param callback the callback to call when finished | |
* @since 2.0 | |
*/ | |
public static void saveFile(final Context context, final byte[] fileBytes, final File outFile, final FileSaveAsynchronousCallback callback) { | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
final File savedFile = saveFile(fileBytes, outFile); | |
Handler mainHandler = new Handler(context.getMainLooper()); | |
Runnable myRunnable = new Runnable() { | |
@Override | |
public void run() { | |
if (callback != null) { | |
callback.finish(savedFile); | |
} | |
} | |
}; | |
mainHandler.post(myRunnable); | |
} | |
}).start(); | |
} | |
/** | |
* Save an file in the application file directory *ASYNCHRONOUS* | |
* | |
* @param context the context of the application | |
* @param fileBytes the byte to save | |
* @param directoryName the directory name | |
* @param fileName the filename | |
* @param callback the callback to call when finished | |
* @since 2.0 | |
*/ | |
public static void saveFile(final Context context, final byte[] fileBytes, final String directoryName, final String fileName, final boolean inCache, final FileSaveAsynchronousCallback callback) { | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
final File outFile = saveFile(context, fileBytes, directoryName, fileName, inCache); | |
Handler mainHandler = new Handler(context.getMainLooper()); | |
Runnable myRunnable = new Runnable() { | |
@Override | |
public void run() { | |
if (callback != null) { | |
callback.finish(outFile); | |
} | |
} | |
}; | |
mainHandler.post(myRunnable); | |
} | |
}).start(); | |
} | |
/** | |
* Save an file in the application file directory *SYNCHRONOUS* | |
* | |
* @param context the context of the application | |
* @param fileBytes the byte to save | |
* @param directoryName the directory name | |
* @param fileName the filename | |
* @since 2.0 | |
*/ | |
public static File saveFile(final Context context, final byte[] fileBytes, final String directoryName, final String fileName, final boolean inCache) { | |
final File outFile; | |
if (inCache) { | |
outFile = getCacheFile(context, directoryName, fileName); | |
} else { | |
outFile = getDataFile(context, directoryName, fileName); | |
} | |
return saveFile(fileBytes, outFile); | |
} | |
/** | |
* Save an file in a specified file | |
* | |
* @param fileBytes the byte to save | |
* @param outFile the file to write in | |
* @since 2.0 | |
*/ | |
private static File saveFile(final byte[] fileBytes, final File outFile) { | |
try { | |
outFile.getParentFile().mkdirs(); | |
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile)); | |
bos.write(fileBytes); | |
bos.flush(); | |
bos.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return outFile; | |
} | |
/** | |
* Copy a file from an inputstream | |
* | |
* @param inputStream the input stream of the file | |
* @param outFile the destination | |
* @return the file to write in | |
*/ | |
public static File copyFile(@NonNull final InputStream inputStream, final File outFile) { | |
try { | |
outFile.getParentFile().mkdirs(); | |
OutputStream outStream = new FileOutputStream(outFile); | |
byte[] buffer = new byte[4 * 1024]; | |
int bytesRead; | |
while ((bytesRead = inputStream.read(buffer)) != -1) { | |
outStream.write(buffer, 0, bytesRead); | |
} | |
IOUtils.closeQuietly(inputStream); | |
IOUtils.closeQuietly(outStream); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return outFile; | |
} | |
/** | |
* Clear a specified folder in the cache | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @since 2.0 | |
*/ | |
public static void removeAllFiles(final Context context, final String directoryName, final boolean inCache) { | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
final File dir; | |
if (inCache) { | |
dir = getCacheDir(context, directoryName); | |
} else { | |
dir = getDataDir(context, directoryName); | |
} | |
removeFilesInDir(dir); | |
} | |
}).start(); | |
} | |
/** | |
* Remove the specified folder | |
* | |
* @param context the context of the application | |
* @param directoryName the directory name | |
* @since 2.0 | |
*/ | |
public static void removeFolder(final Context context, final String directoryName, final boolean inCache) { | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
final File dir; | |
if (inCache) { | |
dir = getCacheDir(context, directoryName); | |
} else { | |
dir = getDataDir(context, directoryName); | |
} | |
removeFilesInDir(dir); | |
dir.delete(); | |
} | |
}).start(); | |
} | |
/** | |
* Clear a specified folder | |
* | |
* @param directory the directory file | |
* @since 2.0 | |
*/ | |
private static void removeFilesInDir(File directory) { | |
if (directory == null || !directory.isDirectory()) { | |
return; | |
} | |
String[] children = directory.list(); | |
for (String aChildren : children) { | |
File child = new File(directory, aChildren); | |
if (child.isDirectory()) { | |
removeFilesInDir(child); | |
} else { | |
child.delete(); | |
} | |
} | |
} | |
/** | |
* Get a intent chooser for a view file | |
* @param context the context of the application | |
* @param uri the file uri | |
* @since 2.0 | |
* @return the intent | |
*/ | |
@Nullable | |
public static Intent getIntentForFileUri(@NonNull Context context, @NonNull Uri uri) { | |
String type = getMimeTypeForUri(context, uri); | |
if (type == null) { | |
return null; | |
} | |
try { | |
Intent openIntent = new Intent(Intent.ACTION_VIEW); | |
openIntent.setDataAndType(uri, type); | |
openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); | |
openIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); | |
return Intent.createChooser(openIntent, ""); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
/** | |
* Get the mimetype of an uri | |
* @param context the context of the application | |
* @param uri the file uri | |
* @since 2.0 | |
* @return the mimetype | |
*/ | |
@Nullable | |
public static String getMimeTypeForUri(@NonNull Context context, @NonNull Uri uri) { | |
String mimeType = null; | |
if (Objects.equals(uri.getScheme(), ContentResolver.SCHEME_CONTENT)) { | |
ContentResolver cr = context.getContentResolver(); | |
mimeType = cr.getType(uri); | |
} else { | |
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri | |
.toString()); | |
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( | |
fileExtension.toLowerCase()); | |
} | |
return mimeType; | |
} | |
/** | |
* Get a public URI for a file | |
* | |
* @param context the context of the application | |
* @param file the file | |
* @return the uri | |
*/ | |
@Nullable | |
public static Uri getShareableUri(@NonNull Context context, @NonNull File file) { | |
if (!file.exists()) { | |
return null; | |
} | |
return FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file); | |
} | |
/** | |
* Create an temporary file in the public space | |
* | |
* @param context the context of the application | |
* @return the file | |
*/ | |
@Nullable | |
public static File getNewTemporaryPublicPictureFile(@NonNull Context context) { | |
// Create an image file name | |
String imageFileName = UUID.randomUUID().toString(); | |
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); | |
File file = null; | |
try { | |
file = File.createTempFile( | |
imageFileName, /* prefix */ | |
".jpg", /* suffix */ | |
storageDir /* directory */ | |
); | |
file.getParentFile().mkdirs(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return file; | |
} | |
/** | |
* Create an temporary file in the public space for a document | |
* | |
* @param context the context of the application | |
* @return the file | |
*/ | |
@Nullable | |
public static File getNewTemporaryPublicDocumentFile(@NonNull Context context, @NonNull String mimeType) { | |
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); | |
String imageFileName = UUID.randomUUID().toString(); | |
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS); | |
File file = null; | |
try { | |
file = File.createTempFile( | |
imageFileName, /* prefix */ | |
"."+ extension, /* suffix */ | |
storageDir /* directory */ | |
); | |
file.getParentFile().mkdirs(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return file; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment