把android数据库复制到sd卡

来源:互联网 发布:windows如何录制视频 编辑:程序博客网 时间:2024/05/06 03:51
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business


}


if (mIsInitializing) {
throw new IllegalStateException(
"getWritableDatabase called recursively");
}


// If we have a read-only database open, someone could be using it


// (though they shouldn't), which would cause a lock to be held on


// the file, and our attempts to open the database read-write would


// fail waiting for the file lock. To prevent that, we acquire the


// lock on the read-only database, which shuts out other users.


boolean success = false;
SQLiteDatabase db = null;
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);

} else {

//得到sd卡ostocy/db/db文件的路径

String path = getDatabasePath(mName)
.getPath();

db = SQLiteDatabase.openOrCreateDatabase(path, null);
//InputStream myInput=getResources().openRawResource(R.raw.atcoffeejshopmactive);
InputStream myInput = null;
//读取assets目录下的db文件
 myInput = getClass().getResourceAsStream("/assets/db/atcoffeejshopmactive.db");


File fo=new File(path);
// Open the empty db as the output stream
OutputStream myOutput = null;
try {
myOutput = new FileOutputStream(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try {
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}


onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
}
}
mDatabase = db;
} else {
if (db != null)
db.close();
}
}