为什么尝试将SQLite数据库从资产复制到手机内存时没有创建文件?



我正在使用GreenDAO作为ORM,并使用由SQLite Cipher加密的预填充数据库。加密是GreenDAO的功能。因此,当用户启动应用程序时,我使用以下代码将数据库从资产复制到手机内存。

ContextWrapper cw =new ContextWrapper(context);
if (android.os.Build.VERSION.SDK_INT >= 17) {
DB_PATH = cw.getApplicationInfo().dataDir + "/databases/";  
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
byte[] buffer = new byte[1024];
OutputStream myOutput = null;
int length;
InputStream myInput = null;
try
{
myInput = mContext.getAssets().open(DB_NAME);
myOutput =new FileOutputStream(DB_PATH+ DB_NAME);
while((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
myOutput.close();
myOutput.flush();
myInput.close();

但是在某些设备上,它显示以下错误

"Exception java.io.FileNotFoundException:/data/user/0/com.example.appname/databases/my-db.db: open failed: ENOENT (No so file or directory) ">

根据Firebase崩溃报告,以下行是造成错误的原因。

myOutput =new FileOutputStream(DB_PATH+ DB_NAME);

我该如何解决这个问题,并确保数据库在所有设备上都能工作。但是我正在使用下面的代码来检查数据库是否存在

File file = new File(DB_PATH+ DB_NAME);
if(file.exists()) {
}

目录

/data/user/0/com.example.appname/databases

尚不存在。

在尝试在其中写入文件之前,请检查该目录是否存在,如果没有,请创建它。

if(file.getParentFile().exists()) 
if(!file.getParentFile().mkdirs())
return false.

最新更新