我正在开发一个使用数据库的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;
}
答案 0 :(得分:0)
试试这个::
File sd = Environment.getExternalStorageDirectory();
File src = new File("YOUR_SOURCE_PATH");
File dest = new File(sd + "/" +DATABASE_NAME);
try
{
if (Environment.getExternalStorageDirectory().canWrite())
{
if (srcdb.exists())
{
FileChannel src = new FileInputStream(srcdb).getChannel();
FileChannel dst = new FileOutputStream(destdb).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
flag=0;
}
else
{
Toast.makeText(getApplicationContext(), "ERROR: File not found in Database " , Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "ERROR: Cannot write to file" , Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.e("Movedb", "Error in Copying" + e.toString());
}
此外,您只需要一个权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>