尝试从android中的内部存储读取excel文件(.xlsx)时出现FileNotFound异常



我在安卓手机的内部存储中有一个excel(.xlsx(文件。我可以选择excel文件,但当我创建file对象时,我会得到异常";FileNotFoundException";(目标:-是选择一个excel文件,然后读取它(。

在"活动类"中;导入"--->我有一个按钮,点击一个按钮(即点击方法(我写了下面提到的代码:-

Intent chooseFile = new Intent();
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("*/*");
chooseFile.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(chooseFile, "Choose a file"), PICK_FILE_REQUEST_CODE);

在此之后,在onActivityResult->

@Override

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode==PICK_FILE_REQUEST_CODE)
{
try {
Uri uri = data.getData();            
File file = new File(uri.getPath());

FileInputStream myInputStream=new FileInputStream(file);
OPCPackage myFileSystem=OPCPackage.open(myInputStream);
XSSFWorkbook myWorkBook=new XSSFWorkbook(myFileSystem);
XSSFSheet mySheet=myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator= mySheet.rowIterator();
int rowNumber=0;
while(rowIterator.hasNext())
{

XSSFRow myRow=(XSSFRow) rowIterator.next();
if(rowNumber!=0)
{
Iterator<Cell> cellIterator=myRow.cellIterator();
int columnNumber=0;
while(cellIterator.hasNext())
{
XSSFCell myCell=(XSSFCell) cellIterator.next();
if(columnNumber==0)
{
String Name=myCell.toString());
}
if(columnNumber==1)
{
String RollNumber=myCell.toString());
}
columnNumber++;
}
}
rowNumber++;
}
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}

AndroidManifest.xml-->

添加了权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<application>
<activity android:name=".ui.home.Import"/>  //not a launcher activity
</application>

我试了很多次在网上找到答案,但到目前为止我还不能正确地找到。经过大量的尝试和参考,我把这个问题放在这里,如果我能知道我做错了什么,这将非常有帮助。

File file = new File(uri.getPath());
FileInputStream myInputStream=new FileInputStream(file);

更改为:

InputStream myInputStream = getContentResolver().openInputStream(data.getData());

你有一个很好的内容方案uri,所以使用它。

最新更新