Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

android - Cannot write to SD card -- canWrite is returning false

Sorry for the ambiguous title but I'm doing the following to write a simple string to a file:

try {
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()){
            System.out.println("Can write.");
            File def_file = new File(root, "default.txt");
            FileWriter fw = new FileWriter(def_file);
            BufferedWriter out = new BufferedWriter(fw);
            String defbuf = "default";
            out.write(defbuf);
            out.flush();
            out.close();
        }
        else
            System.out.println("Can't write.");
}catch (IOException e) {
        e.printStackTrace();
}

But root.canWrite() seems to be returning false everytime. I am not running this off of an emulator, I have my android Eris plugged into my computer via USB and running the app off of my phone via Eclipse. Is there a way of giving my app permission so this doesn't happen?

Also, this code seems to be create the file default.txt but what if it already exists, will it ignore the creation and just open it to write or do I have to catch something like FileAlreadyExists(if such an exception exists) which then just opens it and writes?

Thanks for any help guys.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there a way of giving my app permission so this doesn't happen?

You need the WRITE_EXTERNAL_STORAGE permission.

You also need to not have the SD card mounted on your development machine -- either the computer or the phone can access the SD card, but not both at the same time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...