Working with big files
suggest changeSmall files are processed in a fraction of a second, and you can read or write them where you need that. However, if the file is bigger or otherwise slower to process, you may need to use AsyncTask in Android to work with the file in the background:
class FileOperation extends AsyncTask<String, Void, File> {
@Override
protected File doInBackground(String... params) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "bigAndComplexDocument.odf");
FileOutputStream out = new FileOutputStream(file);
... (write the document)
out.close();
return file;
} catch (IOException ex) {
Log.e("FileOperation", "Unable to write", ex);
return null;
}
}
@Override
protected void onPostExecute(File result) {
// This is called when we finish
}
@Override
protected void onPreExecute() {
// This is called before we begin
}
@Override
protected void onProgressUpdate(Void... values) {
// Unlikely required for this example
}
}
DIRECTORY_DOCUMENTS is API 19. Writing that shared file needs WRITE_EXTERNAL_STORAGE on Android 6.0 through 9.
and then
new FileOperation().execute("Some parameters");
This SO question contains the complete example on how to create and call the AsyncTask. Also see the question on error handling on how to handle IOExceptions and other errors.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents