0

您好,我正在构建一个使用 12Mb 数据库的小应用程序。由于数据库大小,我必须从资产文件夹中复制它,我使用字节数组将数据复制到一个空文件:

@Override
public void onCreate(SQLiteDatabase db){

   try{

      //Getting the asset db
      InputStream myInput = this.context.getAssets().open("dicoMots.db");

      //Creating the empty db to receive bytes
      String outFileName = "/data/data/"+this.context.getApplicationContext().getPackageName()+"/databases/dicoMots.db";
      OutputStream myOutput = new FileOutputStream(outFileName);

      //Transfer bytes from the inputfile to the outputfile
      byte[] buffer = new byte[14336000];

      int length;
      while ((length = myInput.read(buffer)) > 0){
          myOutput.write(buffer, 0, length);
      }

      //Close the streams
      myOutput.flush();
      myOutput.close();
      myInput.close();      

      Log.d("DICO", "Database loaded");
   }
   catch(Exception e){
       Log.d("DICO", "Database load fail");
   }
}

空文件创建成功,输入文件也被读取。myInput.read 返回的值也是正确的。但是输出文件仍然是空的并且没有数据被复制。

4

1 回答 1

0

这种方法对我有用

private void copyDataBase() throws IOException {

    InputStream myInput = myContext.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
}
于 2013-08-17T09:36:48.307 回答