我正在开发一个使用数据库的 Android。我想在使用真机运行时将数据库复制到 SD 卡。但它并不总是成功。我的程序没有说明原因,只是它无法复制数据库。我将数据库存储在res\raw\mobilephone1.db
;它是 10 MB。我设置了允许将数据写入 SD 卡的权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
这是正确的吗?
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/mobilephone";
private final String DATABASE_FILENAME = "mobilephone.db";
private SQLiteDatabase openDatabase()
{
try
{
// obtain absolute path of mobilephone.db
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
// if/sdcard/mobilephone exist,crtate this list
if (!dir.exists()) {
dir.mkdir();
}
// if mobilephone.db file did not exist in/sdcard/mobilephone then copy this filt to SD card list(/sdcard/mobilephone) from res\raw
if (!(new File(databaseFilename)).exists())
{
// obtain the InputStream object that encapsulate mobilephone.db
InputStream is = getResources().openRawResource(R.raw.mobilephone1);
FileOutputStream fos = new FileOutputStream(databaseFilename);
int count = 0;
while (count == 0) {
count = is.available();
}
byte[] buffer = new byte[count];
int readCount = 0; // the number of bytes that has successfully readen
while (readCount < count) {
readCount += is.read(buffer, readCount, count - readCount);
}
fos.write(buffer, 0, count);
fos.close();
is.close();
}
// go to mobilephone.db in /sdcard/mobilephone
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
}
catch (Exception e)
{
}
return null;
}