1

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?

andro-girl
  • 7,989
  • 22
  • 71
  • 94

3 Answers3

4

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();
}
throrin19
  • 17,796
  • 4
  • 32
  • 52
0

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());
            }
Nirali
  • 13,571
  • 6
  • 40
  • 53
0

Try with:

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

Also check this - Creating a directory in /sdcard fails

Community
  • 1
  • 1
AkashG
  • 7,868
  • 3
  • 28
  • 43