2012-01-11 5 views
1

現在、私の資産フォルダから/ data/data/packageフォルダにデータベースをコピーしています。私は/データ/データ/パッケージフォルダにコピーする前にファイルを圧縮しようとしています、Zip DBをAndroidにコピー/解凍するときのSQLiteException

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ダウンロードにスペースを節約するために:これは動作するコード(from the answer here)、です。

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

私は唯一のzip圧縮されている、私はからコピーしていたファイル以外は何も変わっていません私が以前にコピーしていたバージョン。最終的なデータベースは適切なサイズなので、まだ圧縮されていないようです...誰かが何か提案や可能性のある理由があれば、それは開かないでしょう、それは大歓迎です。

答えて

2

あなたはこれらの行を削除する必要があります。

あなた BufferedOutputStream
outputStream.flush(); 
outputStream.close(); 

は、おそらくいくつかのバッファリングされたバイトがありますが、あなたはdest.flush()を呼び出す前に、あなたはoutputStreamを閉じているので、それらのバイトは、実際にファイルに書き込まれることはありません。

+0

ありがとうございました! – Stephanie

関連する問題