在我的应用程序中,用户可以使用隐式意图 ACTION_OPEN_DOCUMENT_TREE 来选择要创建 Excel 文件的目录。然而,在 onActivityResult() 中返回的 Uri 不能被 FileOutputStream() 使用,它会抛出 FileNotFoundException 异常。
如果我使用
java.io.FileNotFoundException: content:/com.android.externalstorage.documents/tree/home%3A:test.xlsx (No such file or directory)
在onActivityResult()
中,我通过File.exists()
检查路径是否存在,如果不存在,我想创建一个新的Excel文件。
onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
Log.d(TAG, "onActivityResult: called");
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 2) {
Log.d(TAG, "onActivityResult: path = " + data.getData()
.getPath());
Uri treePath = data.getData();
File path = new File(treePath + File.pathSeparator + "test.xlsx");
if (path.exists()) {
updateExistingExcelFile(path);
} else {
createNewExcelFile(path);
}
}
}
createNewExcelFile():
private void createNewExcelFile(File path) {
Log.d(TAG, "createNewExcelFile: called");
Workbook workbook = new HSSFWorkbook();
Cell cell;
Sheet sheet;
sheet = workbook.createSheet("Name of sheet");
Row row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("Number");
sheet.setColumnWidth(0, (10 * 200));
sheet.setColumnWidth(1, (10 * 200));
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(path);
workbook.write(fileOutputStream);
Toast.makeText(this, "Created", Toast.LENGTH_LONG)
.show();
fileOutputStream.close();
} catch (IOException e) {
Log.e(TAG, "createNewExcelFile: ", e);
}
}
如果我使用
Activity.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
或类似的内容来替换隐式意图路径,这段代码就能正常运行。