Android外部数据库的引用
情景:有现成的数据库,需要在项目中使用。
1.将数据库拷贝到main文件夹下的assets文件夹中(assets文件夹需自己创建,且文件夹名称必须为assets,否则AS无法编译)
2.一般是在APP的引导界面将已有数据库拷贝到App的目录中去
3.对数据库进行操作。
将数据库拷贝到App中的方法如下
private void copydatabase(String dbname) {
//getFilesDir:拿到data-data当前目录下的files文件夹的绝对路径
File file = new File(getFilesDir(), dbname);
if (!file.exists()){//判断db是否存在
AssetManager assets = getAssets();
FileOutputStream fos = null;
InputStream is = null;
try {
//拿到输入流
is = assets.open(dbname);
//读写
fos = new FileOutputStream(file);
//缓冲区
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
AI 代码解读