在昨晚我的手机更新之前,我的代码运行良好。
我正在使用 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,我现在可以让代码再次运行。
他们的解决方案是
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));
关于java - Android更新后opencsv不读取CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65957624/