将压缩数据库复制/解压缩到Android上时的SQLiteException

时间:2012-01-11 16:39:00

标签: android sql database zip

目前,我正在将数据库从我的assets文件夹复制到/ data / data / package文件夹。这是代码(from the answer here),它起作用:

public void copyDataBase() throws IOException{
    // open db as input stream
    InputStream myInput;
    //open empty db as output stream
    OutputStream myOutPut;
    try {
        myInput = myContext.getAssets().open(DB_NAME);

        //path to newly created db
        String outFileName =DB_PATH + DB_NAME;

        myOutPut = new FileOutputStream(outFileName);

        //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);
        }
        myOutPut.flush();
        myOutPut.close();
        myInput.close();
        }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

现在为了节省.apk下载空间,我试图在将文件复制到/ data / data / package文件夹之前压缩文件。

private void copyDataBaseFromZipFile() {
    InputStream inputStream = null;
    OutputStream outputStream = null;

    String sourcePathname = this.getBundledPathname();
    String destinationPath = this.getDatabasePathname();

    try {
        inputStream = this.mContext.getAssets().open(sourcePathname);
        ZipInputStream zipStream = new ZipInputStream(inputStream);

        int BUFFER = 8096;
        outputStream = new FileOutputStream(destinationPath);
        BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER);

        ZipEntry entry;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (entry.getName().equals("androidDB.sql")) }
                int count;
                byte data[] = new byte[BUFFER];
                while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
            }
        }

        outputStream.flush();
        outputStream.close();

        dest.flush();
        dest.close();

        zipStream.close();

        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

当我稍后尝试打开数据库时(使用SQLiteDatabse),我收到此错误:android.database.sqlite.SQLiteException: unable to open database file

我没有更改任何内容,除了我要复制的文件,这只是我之前复制的文件的压缩版本。最终的数据库大小合适,所以它似乎没有被压缩...如果有人有任何建议或可能的原因为什么它不会打开,我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

你应该删除这些行:

outputStream.flush();
outputStream.close();

您的BufferedOutputStream可能有一些缓冲字节,但由于在调用outputStream之前关闭dest.flush(),这些字节实际上从未写入文件。