1

I know, this question has been asked a thousand times, but no solution worked for me... I simply want to save data into a file on the SD card. But first, here's my code:

private static final String TAG="Logmessage";

public void save(){
    String state=Environment.getExternalStorageState();
    if(Environment.MEDIA_MOUNTED.equals(state)){
        File dir=new File(Environment.getExternalStorageDirectory() + "/NewFolder");
        if(!dir.exists()){
            if (dir.mkdirs()){
                Log.i(TAG,"Dir made");
            }else{
                Log.i(TAG,"Error: Dir not made");
            }
        }else{
            Log.i(TAG,"Dir already exists");
        }
        File file=new File(dir,"file.txt");
        try {
            BufferedWriter bWriter = new BufferedWriter(new FileWriter(file));
            bWriter.write("Hello World!");
            bWriter.close();
        }catch (IOException e){
            Log.e("Exception","BufferedWriter");
        }
    }else{
        Log.i(TAG,"External Drive not available");
    }
}

Of course I added <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the manifest file, but when I run the app, the log messages are always: Logmessage: Dir not made and Exception: BufferedWriter. So I suppose, the entry in the manifest file didn't "work", because it couldn't even create the directory?

  • Are you targetting Android > 5.0? Storage permissions have changed drastically, read it up on Google's Android Developer site. – t0mm13b May 18 '16 at 22:56
  • That was the problem! I looked it up on http://stackoverflow.com/questions/33162152/storage-permission-error-in-marshmallow – Jonas Süskind May 19 '16 at 09:39

1 Answers1

0

This code working perfect for me :

String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that 
//any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
        , "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
 //then write file
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
        File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
 //then write file
}

You can use File.separator instead of "/"

And if external is not available this code will create same folder in internal storage by default

Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58