简体   繁体   中英

android: writing to sdcard fails - why?

i have a problem with my code that is supposed to write some data string to my sdcard. i use a class to do this:

public class CVS {
    private String path;
    private String filename;

    private File dir;
    private File file;

    private FileWriter fw;

    public CVS() {
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/traffic/";
        filename = "data.cvs";
        file = new File(path, filename);    
        createDir();
    }

    private void createDir() {
        dir = new File(path);   
        if(!dir.exists()) {
            if(file.mkdirs() == false) {
                Log.d(Config.LOGTAG, "UHOH!!!!!!!!!!!!!!!!!!!!!!!!");
            }
        }
        else Log.d(Config.LOGTAG, "dir exists");
    }

    public void writeToFile(String data) {
        try {
            fw = new FileWriter(file);  
            fw.append(data); Log.d(Config.LOGTAG, "data saved to file...");
        }
        catch(Exception e) {
            Log.d(Config.LOGTAG, "file: " + e.getMessage());
        }
    }
}

this results ALWAYS in an exeption being caught in writeToFile(), saying "permission denied". actually, i set permissions to WRITE_EXTERNAL_STORAGE in the manifest. so - what am i doing wrong!?

additional info: real device with sd card mounted. no emulator. android 2.2. if i create the dir myself, the problem wont go away :(

Either:

  • Your manifest is wrong, or
  • Your external storage is mounted on your development machine, or
  • Your manual concatenation of your directory is wrong

Your code is ok but still you can add a check for whether sdcard is inserted or not, if you run this code and sdcard is not inserted then it will throw an exception, good practice is that you should always catch the exeptions. you can check sdcard by following code...

if (android.os.Environment.getExternalStorageState().equals
                (android.os.Environment.MEDIA_MOUNTED))
 {
     //code or logic if sd card is inserted....
 }
 else
 {
     Log.e("Exception","SD Card not found!");
 }

All of the answers are needed, but if it's a Samsung device, then you need to append "/external_sd/" to the path - because they decided they needed to dork with our minds and break the API:

" http://developer.samsung.com/forum/board/thread/view.do?boardName=GeneralB&messageId=162934&messageNumber=1381&startId=zzzzz~&searchType=TITLE&searchText=sdcard

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