In reference to question
Can anyone explain the File() parameters used to download file in android?
Can I do it without creating virtual SD Card. Is the开发者_JS百科re any way to save the file in phone memory in internal memory? if it is possible without using the virtual SD Card, then how?
your question is a bit unclear about which you want to use, so here's both.
Like mbaird said, you can easily save a file to the phone's internal storage using
Context.openFileOutput()
. For example:
// Create file on internal storage and open it for writing
FileOutputStream fileOut;
try {
fileOut = openFileOutput(userId +".ics", Context.MODE_PRIVATE);
} catch (IOException e) {
// Error handling
}
// Write to output stream as usual
// ...
This would create a new file on the phone's internal storage, at a path like this:
/data/data/com.example.yourpackagename/files/123456.ics
.
Only your application can read this file; others will not be able to read this file, like they would if it was on the SD card.
If you want to save a file to the SD card, you need something like this:
if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
// SD card is not available
return;
}
File root = Environment.getExternalStorageDirectory() +"/myapp/";
File newFile = new File(root, userId +".ics");
FileOutputStream fileOut = new FileOutputStream(newFile);
// Write to output stream as usual
// ...
As you can see, you cannot rely on an SD card being present and available for writing to at any given point in time. This could be for several reasons:
- The device/emulator has no SD card
- The SD card is being shared with the PC
- The SD card is read-only
- The SD card has no file system
- The SD card is corrupt
If you do Context.openFileOutput() and give it just a filename like "myfile.txt" without a path, it should create the file in your app's data directory, not the SD card.
精彩评论