I am trying to copy files from a location on the device to the app folder, and using:
public static void copyFile(final String srcAbsolutePath, final String dstAbsolutePath) throws IOException {
FileInputStream srcFileStream = null;
FileOutputStream dstFileStream = null;
try {
srcFileStream = new FileInputStream(srcAbsolutePath);
dstFileStream = new FileOutputStream(dstAbsolutePath);
byte[] writeBytes = new byte[1024];
int bytesCount;
while ((bytesCount = srcFileStream.read(writeBytes)) > 0) {
dstFileStream.write(writeBytes, 0, bytesCount);
}
} catch (IOException ex) {
Log.e(TAG, "Failed to copy the file from src="+srcAbsolutePath+" to="+dstAbsolutePath, ex);
throw ex;
} finally {
// close the streams
if (srcFileStream != null) {
srcFileStream.close();
}
if (dstFileStream != null) {
dstFileStream.close();
}
}
}
and I am running into this error:
Failed to copy the file from src=/root/storage/emulated/0/TestApp/1a5e67e1-c166-4a52-abb4-3de61898e109.pdf to=/data/user/0/com.myapp.package/files/78e6a56b-3141-4024-a3a1-f3f44ccc6dfb.pdf
java.io.FileNotFoundException: /root/storage/emulated/0/TestApp/1a5e67e1-c166-4a52-abb4-3de61898e109.pdf (Permission denied)
I have the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am using https://github.com/spacecowboy/NoNonsense-FilePicker to pick the file (Uri).
I have the following in AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/nnf_provider_paths" />
</provider>
How to fix the error?
Finally found an utility in NoNonsense-FilePicker (getFileForUri):