Error While Creating New File In Sd Card Using Documentfile.createfile();
I am trying to create a new File in SD Card for Android 5.0 and above. So first I am making the user grant the permission through SAF. This is how I am check if the selected Direct
Solution 1:
Continue from this answer now that you have the DocumentFile (which is a directory to create a file inside it) through the loop just use myDocumentFile.createFile(...) to create a new file on your desired directory.
// creating the fileDocumentFiledocumentFileNewFile= documentFileGoal.createFile(myMimeType,
myNewFileName);
Then stream to it
outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
inputStream = new FileInputStream(myInputFile);
...
if (outputStream != null) {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
}
...
...
...
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
Edite
Prevent findFile on a null DocumentFile by checking the value of rootDocFile on each loop. (happens when the user selects a wrong path instead of the sd-card)
for (int i = 3; i < parts.length; i++)
{
if (rootDocFile != null) {
rootDocFile = rootDocFile.findFile(parts[i]);
}
}
Post a Comment for "Error While Creating New File In Sd Card Using Documentfile.createfile();"