Android CSV 路径抛出 FileNotFoundExpception

Android CSV Path is throwing FileNotFoundExpception

我想从外部存储导入 csv,然后更新我的数据库,但是当我从下载的文件夹中选择 csv 时 FileNotFoundExpception 出现了。这是例外 System.err:

java.io.FileNotFoundException: /document/primary:Download/GuestCSV.csv: open failed: ENOENT (No such file or directory)

这是我的代码。请查看我的代码并帮助我找到解决方案。

        importDatabase.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("text/*");
            startActivityForResult(Intent.createChooser(intent, "Open CSV"), ACTIVITY_CHOOSE_FILE);
        }
    });
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ACTIVITY_CHOOSE_FILE: {
            if (resultCode == RESULT_OK) {
                onImport(new File(data.getData().getPath()));
                Log.d(TAG, data.getData().getPath());
            }
        }
    }
}

public void onImport(File files) {
    try {
        String[] nextLine;
        try {
            CSVReader reader = new CSVReader(new FileReader(files.getAbsolutePath()));
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                String emailID = nextLine[0];
                String guestName = nextLine[1];
                String guestSource = nextLine[2];
                String guestPhone = nextLine[3];
                String guestCount = nextLine[4];
                String guestCreatedDate = nextLine[5];
                String guestModifiedDate = nextLine[6];
                GuestDetails guestDetails = new GuestDetails();
                guestDetails.setEmail(emailID);
                guestDetails.setUsername(guestName);
                guestDetails.setPhone(guestPhone);
                guestDetails.setSource(guestSource);
                guestDetails.setCount(Integer.valueOf(guestCount));
                guestDetails.setCreatedDate(guestCreatedDate);
                guestDetails.setModifiedDate(guestModifiedDate);
                try {
                    helper.insertGuest(guestDetails);
                } catch (SQLiteConstraintException e) {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), "Data inserted into table...", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

无法保证您作为结果收到的 URI 是一个文件(因此路径部分是一个实际的文件系统路径)。

它可能是一个 content: URI,如果路径只对相应的 ContentProvider 有意义。

应该使用ContentResolver.openInputStream() or queried via ContentResolver.query()读取这种URI。

有关详细信息,请参阅 A Uri Is Not (Necessarily) a File