我从String path = uri.getPath()
获取了/document/primary:Download/West Delhi Mis June.xlsx
但是当我写File file = new File(path)
时,它会抛出FileNotFoundException
。请帮忙。
这是我的代码:
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);
}
}
}
答案 0 :(得分:5)
您无法直接将Uri转换为文件 Uri甚至可能不包含真正的绝对路径。
这是因为它可能必须通过来自不同应用程序的ContentProvider来为您提供实际文件,这是Nougat的新文件安全模型的所有部分。
那你能做什么?让操作系统将其作为InputStream打开:
Uri uri = ...
InputStream dataStream = context.getContentResolver().openInputStream(uri);
// now buffer and read stream