我想从uri读取fileInputStream,但返回未找到的文件异常
到目前为止,这是我的代码:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri fileUri = data.getData();
long size = Helper.GetFileSize(getActivity(),fileUri);
File F = new File(fileUri.getPath());
Log.d("File", "File Uri: " + fileUri.toString());
FileInputStream fis;
try {
fis = new FileInputStream(new File(F.getPath()));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
最佳答案
问题是路径包含content:// ....,而File需要具有实际的filePath
尝试更新您的代码片段中的以下内容:
Uri fileUri = data.getData();
String filePath = getPathFromUri(this,fileUri);
long size = Helper.GetFileSize(getActivity(),filePath);
File F = new File(filePath);
这是帮助的方法
public String getPathFromURI(Context context, Uri contentUri) {
Cursor mediaCursor = null;
try {
String[] dataPath = { MediaStore.Images.Media.DATA };
mediaCursor = context.getContentResolver().query(contentUri, dataPath, null, null, null);
int column_index = mediaCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
mediaCursor.moveToFirst();
return mediaCursor.getString(column_index);
} finally {
if (mediaCursor != null) {
mediaCursor.close();
}
}
}
关于java - 尝试从android中的uri读取时找不到文件异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39025943/