at010
at010

Reputation: 137

Cannot write to a file on Android device

I am trying to use CSVWriter to write to a file for my android project.

As part of my folder structure I have created a folder called myData and within that have a CSV file called results.csv

String csvpath = Environment.getExternalStorageDirectory().getAbsolutePath();
CSVWriter csvw = new CSVWriter(new FileWriter(csvpath+"/myData/results.csv"));

However I get the following exception

java.io.FileNotFoundException: /storage/emulated/0/myData/results.csv: open failed: ENOENT (No such file or directory)

I have also added:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How can I get the correct path for this file?

Upvotes: 0

Views: 786

Answers (1)

Rathan Kumar
Rathan Kumar

Reputation: 2577

The issue is you have to create the myData Folder Otherwise it will throws the exception.

    File dir=new File( Environment.getExternalStorageDirectory(), "MyDate");
    if(!dir.exists()){
        dir.mkdir();
    }
    CSVWriter csvw = new CSVWriter(new FileWriter(dir.getAbsolutePath()+"/results.csv"));

In Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Upvotes: 1

Related Questions