我在 android 应用程序中有以下代码作为 DataBaseHelper:
public class DbUtils {
private static final String DB_PATH = "/data/data/com.project.skcompanion/databases/";
private static final String DB_NAME = "basesh.sqlite";
public static void createDatabaseIfNotExists(Context context) throws IOException {
Log.d("check1", "check1");
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
boolean doUpgrade = false;
if (doUpgrade) {
dbFile.delete();
createDb = true;
}
}
Log.d("check2", "check2");
if (createDb) {
Log.d("check3", "check3");
// Open your local db
AssetManager am = context.getAssets();
InputStream myInput = am.open(DB_NAME);
Log.d("check4", "check4");
// Open the empty db
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}
public static SQLiteDatabase getStaticDb() {
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
但是当代码尝试打开 basesh.sqlite 时,它会发送 FileNotFoundException。我在资产/数据库中有我的 basesh.sqlite 文件。经过一些调试,我认为问题出在这一行。
InputStream myInput = am.open(DB_NAME);
但我不知道为什么它没有打开我的文件。提前致谢。