Reputation: 1035
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?
Upvotes: 1
Views: 2131
Reputation: 24235
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);
...
}
Upvotes: 2
Reputation: 1706
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...
Upvotes: 3
Reputation: 2065
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");
Upvotes: 0