2012-01-11 82 views
1

当前,我正在将数据库从我的资产文件夹复制到/ data/data/package文件夹。这是代码(from the answer here),它的工作原理:SQLiteException将压缩数据库复制/解压缩到Android

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文件下载,我想将它复制到/数据/数据/包文件夹之前压缩文件。

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

我没有,除了我的文件改变任何东西从,复制这仅仅是一个压缩我之前复制的版本。最终的数据库是正确的大小,所以它似乎还没有被压缩......如果任何人有任何建议或可能的原因为什么它不会打开,它将不胜感激。

回答

2

您应该删除这些行:

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

BufferedOutputStream可能有一些缓冲的字节,但因为你关闭outputStream你打电话之前dest.flush(),这些字节从来没有真正写入文件。

+0

工作,谢谢! – Stephanie 2012-01-11 17:30:47