2012-01-11 95 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