Thursday, November 29, 2012

Copy Android Asset To Internal Storage

Some times a database is deployed with the application as an asset.

However, the database can't be used directly, it must be copied to the storage first.

In this sample code, the asset is copied to the internal storage if it isn't copied yet.
Context Context = getApplicationContext();
String DestinationFile = Context.getFilesDir().getPath() + File.separator + "DB.sqlite";
if (!new File(DestinationFile).exists()) {
  try {
    CopyFromAssetsToStorage(Context, "Database/DB.sqlite", DestinationFile);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
  InputStream IS = Context.getAssets().open(SourceFile);
  OutputStream OS = new FileOutputStream(DestinationFile);
  CopyStream(IS, OS);
  OS.flush();
  OS.close();
  IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
  byte[] buffer = new byte[5120];
  int length = Input.read(buffer);
  while (length > 0) {
    Output.write(buffer, 0, length);
    length = Input.read(buffer);
  }
}
The code assumes that the file to be copied is named 'DB.sqlite' and it resides in a folder named 'database' in the assets.

3 comments:

  1. Thanks. Very helpful post.
    I had to change the database DestinationFile as follows:
    DestinationFile = Context.getDatabasePath("DB.sqlite").getPath();
    The Content Provider could not find the database.

    ReplyDelete
  2. Thanks, i have been finding solution from last 5 days husshh

    ReplyDelete
  3. Thanks, it was very helpful!

    ReplyDelete