andro-girl
andro-girl

Reputation: 8129

file.mkdirs() not working

i want to write to a file in the sdcard of my phone.i used the below code to do this.

private  CSVWriter _writer;
private  File _directory;
public  String _fileTestResult;
private  String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
    _writer=null;
    _directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
    if(!_directory.exists())    
        _directory.mkdirs();

}

public  void exportResult(String testcaseNum,String testcase,String status){


    try {

        if(_directory.exists()){
           //do something
        }

but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.

note:i have given the permission in manifest file.

EDIT: i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?

Upvotes: 1

Views: 5641

Answers (3)

AkashG
AkashG

Reputation: 7888

Try with:

if(!_directory.exists())    
        _directory.mkdir();

Also check this - Creating a directory in /sdcard fails

Upvotes: 0

throrin19
throrin19

Reputation: 18207

have you add the correct permission in your manifest ?

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

Edit : ok, i just read your note for permission.

If it's help you this is my sdcard cache code :

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
        String evtDir = "";
        if(evt > 0){
            evtDir = File.separator + evt;
        }


        cacheDir = new File(
                android.os.Environment.getExternalStorageDirectory()
                        + File.separator 
                        + "Android" 
                        + File.separator 
                        + "data"
                        + File.separator
                        + Application.getApplicationPackageName()
                        + File.separator + "cache"
                        + evtDir);
    }else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

Upvotes: 4

Nirali
Nirali

Reputation: 13825

Try below code

       try {
                File root = Environment.getExternalStorageDirectory();
                if (root.canWrite()) {
                    imagefolder = new File(root,
                            mycontext.getString(R.string.app_name));
                    imagefolder.mkdirs();
                }
            } catch (Exception e) {
                Log.e("DEBUG", "Could not write file " + e.getMessage());
            }

Upvotes: 0

Related Questions