[英]How do i convert the uri from onActivityresult to real file path to import that file
I am getting uri from String path = uri.getPath()
as /document/primary:Download/West Delhi Mis June.xlsx
我从String path = uri.getPath()
获取uri作为/document/primary:Download/West Delhi Mis June.xlsx
But When I write File file = new File(path)
It throws FileNotFoundException
. 但是当我写File file = new File(path)
它抛出FileNotFoundException
。 Please help. 请帮忙。
This is my code: 这是我的代码:
public void getdata(File fil){
try{
Workbook w;
w = Workbook.getWorkbook(fil);
Sheet sheet = w.getSheet(0);
for (int j = 1; j<sheet.getRows(); j++){
Cell c1 = sheet.getCell(0,j);
Cell c2 = sheet.getCell(1,j);
Cell c3 = sheet.getCell(2,j);
Cell c4 = sheet.getCell(3,j);
Cell c5 = sheet.getCell(4,j);
Cell c6 = sheet.getCell(5,j);
Cell c7 = sheet.getCell(6,j);
Cell c8 = sheet.getCell(7,j);
Cell c9 = sheet.getCell(8,j);
Cell c10 = sheet.getCell(9,j);
Cell c11 = sheet.getCell(10,j);
Cell c12 = sheet.getCell(11,j);
Cell c13 = sheet.getCell(12,j);
String date = c1.getContents();
String empid = c2.getContents();
String project = c3.getContents();
String name = c4.getContents();
String route = c5.getContents();
String cabno = c6.getContents();
String location = c7.getContents();
String contact = c8.getContents();
String gender = c9.getContents();
String duty = c10.getContents();
String shift = c11.getContents();
String cabtype = c12.getContents();
String zone = c13.getContents();
adb.insertRoastData(date,empid,project,name,route,cabno,location,contact,gender,duty,shift,cabtype,zone);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void performFileSearch() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
startActivityForResult(intent, READ_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
String path = uri.getPath();
InputStream dataStream = this.getContentResolver().openInputStream(path);
}
}
}
You cannot convert a Uri to a File directly. 您不能将Uri直接转换为文件。
The Uri may not even contain the real, absolute path. Uri甚至可能不包含真实的绝对路径。
This is because it might have to go through a ContentProvider from a different app to serve you the actual file, all part of the new file security model from Nougat. 这是因为它可能必须通过其他应用程序中的ContentProvider才能为您提供实际文件,这是Nougat新文件安全模型的所有部分。
So what can you do? 所以,你可以做什么? Let the OS open it as an InputStream: 让操作系统将其作为InputStream打开:
Uri uri = ...
InputStream dataStream = context.getContentResolver().openInputStream(uri);
// now buffer and read stream
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.