【发布时间】:2018-12-03 08:33:49
【问题描述】:
我正在尝试读取手机内部存储的下载文件夹中的.csv 文件的内容。我的代码如下所示。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
browse = (Button) findViewById(R.id.browse);
editTextPath = (EditText) findViewById(R.id.path);
browse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select file or dir"), 1);
setResult(Activity.RESULT_OK);
Log.e("Content","In onclick");
}
});}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("Content","In onactivity");
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
String path = data.getData().getPath();
Log.e("Pathb",path);
proImportCSV(new File(data.getData().getPath()));
}
}
private void proImportCSV(File file) {
try{
ContentValues cv = new ContentValues();
FileReader fr = new FileReader(file);
CSVReader dataRead = new CSVReader(fr);
String[] vv = null;
while((vv = dataRead.readNext())!=null) {
cv.clear();
}
dataRead.close();
}
catch (Exception e) { Log.e("TAG",e.toString());
}
}
我得到的错误是:
java.io.FileNotFoundException:/document/primary:Download/12132469_About_0_22092018045225.csv:打开失败:ENOENT(没有这样的文件或目录)
我还分享了我的错误截图:
更新
我对之前共享的代码做了一个小改动:
private void proImportCSV(File file, Uri uri) {
try{
ContentValues cv = new ContentValues();
InputStream inputStream = getContentResolver().openInputStream(uri);
InputStreamReader isr = new InputStreamReader(inputStream);
CSVReader dataRead = new CSVReader(isr);
String[] vv = null;
while((vv = dataRead.readNext())!=null) {
cv.clear();
}
dataRead.close();
}
catch (Exception e) { Log.e("TAG",e.toString());
}
}
这里,uri = data.getData()。进行此更改后,我收到以下错误
java.io.FileNotFoundException:/storage/emulated/0/Download/12132469_About_0_22092018045225.csv:打开失败:EACCES(权限被拒绝)
另外,我已经在 manifest.xml 中添加了这行代码
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
【问题讨论】:
-
请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
-
感谢您的建议。我是新来的堆栈溢出问题,所以对此一无所知。下次发帖时会小心的。
标签: java android android-studio android-studio-3.2