简体   繁体   中英

Android Studio: Can't write to external storage?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM