Is It Possible To Save Database File To Sd Card?
Possible Duplicate: Is it possible to copy database file to SD card? I have a database on my Android phone, and I need to get the information onto an SD card. Is it possible to
Solution 1:
Yes. Here is the function that i use:
publicvoidcopyDBToSDCard() {
try {
InputStreammyInput=newFileInputStream("/data/data/com.myproject/databases/"+DATABASE_NAME);
Filefile=newFile(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
Log.i("FO","File creation failed for " + file);
}
}
OutputStreammyOutput=newFileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
byte[] buffer = newbyte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Log.i("FO","copied");
} catch (Exception e) {
Log.i("FO","exception="+e);
}
}
For a project that I worked on, I put a menu option in the home screen that I could call this function from at any time. Then, I'd move the database to my desktop and open it up with the SQLite Manager plugin for FireFox.
Solution 2:
Sure. If this is a database that exists in your app, you can get a reference to the db file via Context.getDatabasePath()
, passing it the database name. From there, it's just a routine file copy operation:
//Get a reference to the databaseFiledbFile= mContext.getDatabasePath("mydb");
//Get a reference to the directory location for the backupFileexportDir=newFile(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
Filebackup=newFile(exportDir, dbFile.getName());
//Check the required operation String command = params[0];//Attempt file copytry {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
Where the method fileCopy()
is defined as:
privatevoidfileCopy(File source, File dest)throws IOException {
FileChannelinChannel=newFileInputStream(source).getChannel();
FileChanneloutChannel=newFileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
HTH!
Post a Comment for "Is It Possible To Save Database File To Sd Card?"