Unable To Access File From Uri
Solution 1:
I am trying to access a file using Storage Access Framework which I have stored in locally and send it to server.
Your users are welcome to choose anything they want, which does not include files that you can access directly (e.g., in Google Drive, on removable storage).
but catches exception when converting to file by getting path
You cannot "convert to file by getting path". The path portion of a content
Uri
is a meaningless set of characters that identifies the particular piece of content. Next, you will think that all computers have a file on their local filesystem at the path /questions/43818723/unable-to-access-file-from-uri
, just because https://stackoverflow.com/questions/43818723/unable-to-access-file-from-uri
happens to be a valid Uri
.
So, get rid of getPath()
.
Use ContentResolver
and openInputStream()
to get an InputStream
on the content. Either use that stream directly or use it in conjunction with a FileOutputStream
on your own file, to make a local copy of the content that you can use as a file.
Solution 2:
@CommonsWare answer is correct here is code snippet
To read file content from Uri :
// Use ContentResolver to access file from UriInputStreaminputStream=null;
try {
inputStream = mainActivity.getContentResolver().openInputStream(uri);
assert inputStream != null;
// read file contentBufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(inputStream));
String mLine;
StringBuilderstringBuilder=newStringBuilder();
while ((mLine = bufferedReader.readLine()) != null) {
stringBuilder.append(mLine);
}
Log.d(TAG, "reading file :" + stringBuilder);
To save file from Uri to local copy inside your app dir :
StringdirPath="/data/user/0/-your package name -/newLocalFile.name"try (InputStreamins= mainActivity.getContentResolver().openInputStream(uri)) {
Filedest=newFile(dirPath);
try (OutputStreamos=newFileOutputStream(dest)) {
byte[] buffer = newbyte[4096];
int length;
while ((length = ins.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
Solution 3:
Try Below Code For Getting Path:
publicString getPath(Uri uri) throws URISyntaxException {
finalboolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to// deal with different Uris.if (needToCheckUri && DocumentsContract.isDocumentUri(mainActivity, uri)) {
if (isExternalStorageDocument(uri)) {
finalString docId = DocumentsContract.getDocumentId(uri);
finalString[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} elseif (isDownloadsDocument(uri)) {
finalString id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} elseif (isMediaDocument(uri)) {
finalString docId = DocumentsContract.getDocumentId(uri);
finalString[] split = docId.split(":");
finalString type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} elseif ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} elseif ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = newString[] {
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = mainActivity.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
}
} elseif ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
returnnull;
}`/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/publicstaticboolean isExternalStorageDocument(Uri uri) {
return"com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/publicstaticboolean isDownloadsDocument(Uri uri) {
return"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/publicstaticboolean isMediaDocument(Uri uri) {
return"com.android.providers.media.documents".equals(uri.getAuthority());
}`
Post a Comment for "Unable To Access File From Uri"