问题描述:对于我们需要使用的外部数据库,首先得将数据库文件放置在android工程的assets目录下。如何就将这个第三方数据库拷贝到应用中供今后的增删改查,是今天需要解决的问题。
解决方案:将数据库文件拷贝到这个目录下(该方法适用于多数文件拷贝): data/data/com.wxk.mobilesafe/files/
代码实现: /**拷贝数据库到files文件夹下
* @param dbName 数据库名称
*/
private void initAddressDB(String dbName) {
//1.在应用中创建files文件夹
File files = this.getFilesDir();
//在files文件夹下创建一个数据库文件
File file = new File(files, dbName);
if (file.exists()) {
return;
}
InputStream stream = null;
FileOutputStream fos = null;
//2.输入流去读取资产目录下的文件
try {
stream = getAssets().open(dbName);
//3.将读取的内容写到指定文件中去
fos = new FileOutputStream(file);
//4.每次的读取内容大小
byte[] bs = new byte[1024];
int temp = -1;
while ((temp = stream.read(bs))!= -1) {
fos.write(bs, 0, temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null && fos != null){
try {
stream.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行应用,发现拷贝完成,data/data/com.wxk.mobilesafe/files/xxx.db 目录下的确出现我们所导入的第三方数据库文件