android sqlite删除包中的数据库

时间:2014-04-06 22:07:43

标签: java android database sqlite delete-file

我使用了以下代码

String destDir = "/data/data/" + getPackageName() +
            "/databases/";
    String destPath = destDir + "jobs";
    File f = new File(destPath);
    if (!f.exists()) {
        //---make sure directory exists---
        File directory = new File(destDir);
        directory.mkdirs();
        //---copy the db from the assets folder into 
        // the databases folder---
        try {
            CopyDB(getBaseContext().getAssets().open("jobs"),
                    new FileOutputStream(destPath));
        } catch (FileNotFoundException e) {     
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public void CopyDB(InputStream inputStream, OutputStream outputStream) 
throws IOException {
    //---copy 1K bytes at a time---
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}

这会将数据库从assets文件夹复制到data / data数据库文件夹中,然后我可以使用它,但前提是它不存在。

我需要能够删除包中的文件,然后在每次应用运行时从资产中复制文件。

我每次都会通过将新数据库复制到assets文件夹来更新数据库中的数据,除非我完全卸载应用程序并重新安装它,否则不会添加新数据。

我想最终从设备上的文件夹加载数据库,这样所有用户必须做的更新就是替换文件,应用程序从新文件中读取,但以后再用。

1 个答案:

答案 0 :(得分:0)

所以...只需删除此行:

 if (!f.exists()) {

及其对应的右括号(})

这将在您运行应用程序时复制db ALWAYS (如果找到它,它会隐式删除该文件)