gpt4 book ai didi

java - 将数据库复制到 SD 卡(如果存在)

转载 作者:行者123 更新时间:2023-12-01 14:15:10 25 4
gpt4 key购买 nike

如果数据库文件存在,如何将其复制到SD卡中?这是我的代码:

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();
}

此代码将数据库复制到内存中。我想检查外部存储器(SD卡)是否存在,如果存在 - 将数据库文件复制到其中,然后在我的应用程序中的任何位置访问它。

最佳答案

试试这个:

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) {
}

不要忘记将其包含在您的 list 文件中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

关于java - 将数据库复制到 SD 卡(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com