Android 更新后 opencsv 不读取 CSV

opencsv not reading CSV after Android update

在我的 phone 昨晚更新之前,我的代码运行良好。 我正在使用 opencsv 将 phones 存储中的 CSV 文件读取到我的应用程序中的数组中。 这是代码...

    public static String[] getFileContents(File file) {
    String[] contentsArray = new String[500];
    if(file.exists()) {
        try {
            CSVReader reader = new CSVReader(new FileReader(file));
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                System.arraycopy(nextLine, 0, contentsArray, 0, nextLine.length);
            }
        } catch (Exception e) {
            System.out.println("Failed file: " + file);
            System.out.println("You are here and sad but at least the file exists");
            e.printStackTrace();
        }
    } else {
        System.out.println("File does not exist");
    }

    return contentsArray;
}

这是我遇到的错误...

I/System.out: Failed file: /storage/emulated/0/Documents/text/36-12644-Test cert-2021.csv
I/System.out: You are here and sad but at least the file exists
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/text/36-12644-Test cert-2021.csv: open failed: EACCES (Permission denied)

我什么都没变。谁能指出我正确的方向来解决这个问题? 新更新 (Android 11) 中是否更改了权限,现在阻止 openCSV 读取文件?

编辑: 这是从 fileExplorer 中引入所选文件的代码...

                    Uri fileUri = data.getData();
                String filePath;
                try {
                    filePath = Utils.getRealPathFromURI(this.getContext(), fileUri);
                    selectedFile = new File(filePath);
                    contentsFromFile = Utils.getFileContents(selectedFile.getAbsoluteFile());

这是获取路径的代码...

    public static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
        return;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

感谢 CommonsWare,我现在可以让代码再次运行了。 他们的解决方案是

delete getRealPathFromURI(). Use ContentResolver and openInputStream() to get an InputStream on the content. Wrap that InputStream in an InputStreamReader. Pass that InputStreamReader to CSVReader.

具体...

InputStream input = this.getContext().getContentResolver().openInputStream(fileUri);
CSVReader reader = new CSVReader(new InputStreamReader(input));