数据库复制到SD卡是否存在 [英] Copy database to sdcard if exists
本文介绍了数据库复制到SD卡是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能复制数据库文件到SD卡,只要它的存在?这里是我的code:
How can I copy database file into sdcard if only it exists? Here is my code:
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();
}
这code复制DATABSE到内部存储器。我要检查,如果外部存储器(SD卡)存在,如果这是真的 - 拷贝数据库文件到它,然后到处访问它在我的应用程序
This code copies databse into internal memory. I want to check if external memory (sdcard) exists, and if it is true - copy database file into it and then access it everywhere in my app.
推荐答案
试试这个:
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//{package name}//databases//{database name}";
String backupDBPath = "{database name}";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel bst = new FileOutputStream(backupDB).getChannel();
bst.transferFrom(src, 0, src.size());
src.close();
bst.close();
}
}
} catch (Exception e) {
}
不要忘了包括这在你的清单文件:
Don't forget to include this in your manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这篇关于数据库复制到SD卡是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文