如果只有它存在,我如何将数据库文件复制到 sdcard 中?这是我的代码:
public boolean checkdatabase() {
boolean checkdb = false;
try {
File databaseFile = myContext.getDatabasePath("database.db");
checkdb = databaseFile.exists();
} catch(SQLiteException e) {
System.out.println("Database doesn't exist");
}
return checkdb;
}
public void opendatabase() {
boolean dbexist = checkdatabase();
if (dbexist) {
myDatabase = SQLiteDatabase.openDatabase("data/data/***/databases/database.db", null, SQLiteDatabase.OPEN_READWRITE);
} else {
createdatabase();
System.out.println("Database doesn't exist");
myDatabase = SQLiteDatabase.openDatabase("data/data/***/databases/database.db", null, SQLiteDatabase.OPEN_READWRITE);
}
}
private copydatabase() throws IOException {
String DB_PATH = "data/data/***/databases/";
File f = new File(DB_PATH);
if (!f.exists()) {
f.mkdir();
}
String DATABASE_NAME = "database.db";
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
此代码将数据库复制到内部存储器中。我想检查外部存储器(sdcard)是否存在,如果它是真的 - 将数据库文件复制到其中,然后在我的应用程序中的任何地方访问它。