[英]opencsv not reading CSV after Android update
在昨晚我的手机更新之前,我的代码一直运行良好。 我正在使用 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;
}
这是我得到的错误......
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,我现在可以让代码再次运行了。 他们的解决方案是
删除getRealPathFromURI() 。 使用ContentResolver和openInputStream()获取内容的InputStream 。 将该InputStream包装在InputStreamReader中。 将该InputStreamReader传递给CSVReader 。
具体来说...
InputStream input = this.getContext().getContentResolver().openInputStream(fileUri);
CSVReader reader = new CSVReader(new InputStreamReader(input));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.