简体   繁体   中英

Android Saving a file to internal memory works while to Sd card fails

I have an Android app where I need to save a file. I create the file like this:

FileOutputStream fOut = openFileOutput(fileName, 
                    MODE_WORLD_READABLE);
            osw = new OutputStreamWriter(fOut);

I open it like this:

FileInputStream srcFileStream = openFileInput(fileName);

This works fine with internal memory files. I've added a prefrences to my app, where the user can select to save the file to the sd card instead. I try this command:

if (Prefs.getCard(this))
        fileName="/sdcard/"+fileName;

Meaning that if the Prefrences is yes, I add "/sdcard/" infront of the file name. The rest of the code remains the same,

This does not seem to work, as I get an Exception:

File /sd/file1 contains a path seperator

How can I use the same code for both saving to SD card and to internal memory, with just a small modification as i tried above?

You certainly didn't forget to add the right permission in the manifest...

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You can also try to access the external path using:

Environment.getExternalStorageDirectory();

I've already seen different external path name, depending on the device...

This should work..

String baseDir = "";
String fileName = "myFile.txt";
FileOutputStream fOut = null;
if (Prefs.getCard(this)) {
    baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir + fileName);
    fOut = new FileOutputStream(file)
}  else {
    fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
}
if (fOut != null) {
    osw = new OutputStreamWriter(fOut);
    ...
}

Edit was beaten to it by Sevens:

You could try something like this:

File f = Environment.getExternalStorageDirectory(); 
String fullfilename = f.getAbsoluteFile() + "/Android/data/NameOfApp/fileshere/" ;

File folderToWrite = new File(fullfilename);
folderToWrite.mkdirs();

File fileToWrite = new File(fullfilename,"filename.txt");

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