Reputation: 19
I am trying to read the contents of a .csv
file which is in my downloads folder of internal storage of my phone. My code looks like this.
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());
}
}
The error I am getting is:
java.io.FileNotFoundException: /document/primary:Download/12132469_About_0_22092018045225.csv: open failed: ENOENT (No such file or directory)
I am also sharing a screenshot of my error:
I made a small change to my previously shared code:
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());
}
}
Here, uri = data.getData()
. After this change I am getting the following error
java.io.FileNotFoundException: /storage/emulated/0/Download/12132469_About_0_22092018045225.csv: open failed: EACCES (Permission denied)
Also, I have already added this lines of code to my manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Upvotes: 1
Views: 3001
Reputation: 10881
You not always can create a working file from a content URI. But you likely don't need it. new CSVReader(fr);
accepts a Reader
as a parameter. You can use InputStreamReader
, created from the InputStream
, created from the Uri
using following method:
InputStream inputStream = getContentResolver().openInputStream(uri);
where uri
is data.getData()
Upvotes: 2