gpt4 book ai didi

java - 如何将 uri 从 onActivityresult 转换为真实文件路径以导入该文件

转载 作者:行者123 更新时间:2023-12-01 16:47:41 25 4
gpt4 key购买 nike

我从String path = uri.getPath()获取uri作为/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);

}
}
}

最佳答案

您无法将 Uri 直接转换为文件。
Uri 甚至可能不包含真实的绝对路径。

这是因为它可能必须通过不同应用程序的 ContentProvider 才能为您提供实际文件,这是 Nougat 的新文件安全模型的所有部分。

那么你能做什么呢?让操作系统将其作为输入流打开:

Uri uri = ...
InputStream dataStream = context.getContentResolver().openInputStream(uri);
// now buffer and read stream

关于java - 如何将 uri 从 onActivityresult 转换为真实文件路径以导入该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46907755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com