Android更新后opencsv不读取CSV

Ala*_*den 6 java android opencsv

在我的手机昨晚更新之前,我的代码运行良好。我正在使用 opencsv 将手机存储中的 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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误...

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)
Run Code Online (Sandbox Code Playgroud)

我什么都没改变。任何人都可以指出我正确的方向来解决这个问题吗?新更新 (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());
Run Code Online (Sandbox Code Playgroud)

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

    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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*den 4

多亏了 CommonsWare,我的代码现在又可以正常工作了。他们的解决方案是

删除getRealPathFromURI()。使用ContentResolveropenInputStream()获取内容的InputStream 。将该InputStream包装在InputStreamReader中。将该InputStreamReader传递给CSVReader

具体来说...

InputStream input = this.getContext().getContentResolver().openInputStream(fileUri);
CSVReader reader = new CSVReader(new InputStreamReader(input));
Run Code Online (Sandbox Code Playgroud)