问题描述
我正在处理一个android项目,该项目应该从存储在android手机外部存储器中的excel文件中提取数据。用于选择文件的代码是。
用于选择文件。
private void browseDocuments(){
String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document",// .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation",// .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",// .xls & .xlsx
"text/plain","application/pdf","application/zip"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
}
} else {
String mimeTypesstr = "";
for (String mimeType : mimeTypes) {
mimeTypesstr += mimeType + "|";
}
intent.setType(mimeTypesstr.substring(0,mimeTypesstr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"),REQUEST_CODE_DOC);
}
关于活动结果
public void onActivityResult(int requestCode,int resultCode,Intent resultData) {
super.onActivityResult(requestCode,resultCode,resultData);
if (requestCode == REQUEST_CODE_DOC
&& resultCode == Activity.RESULT_OK) {
// The result data contains a URI for the document or directory that
// the user selected.
Uri uri = null;
if (resultData != null) {
try {
uri = resultData.getData();
}
catch(Exception e1)
{
Log.d("File",e1.toString());
}
//Perform operations on the document using its URI.
OpenFile(uri);
}
}
}
打开文件的定义
public void OpenFile(Uri uri)
{
try {
File file = new File(uri.toString());
FileInputStream fileInputStream = new FileInputStream(file);
}
catch(Exception e1)
{
Log.d("File",e1.toString());
}
}
2020-10-30 01:23:22.340 22157-22157 / com.example.savemore D /文件:java.io.FileNotFoundException:内容:/com.android.externalstorage.documents/document/primary%3Aexpense.xls (没有这样的文件或目录)
我已经尝试了StackOverflow的许多解决方案,但都没有用。我被困住了。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
也是android:requestLegacyExternalStorage =“ true”
还使用uri,uri.toString,uri.getPath(),file.getAbsolutePath()等对所有内容进行了尝试,但仍然没有任何效果。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)