Skip to content

Instantly share code, notes, and snippets.

@Keshava11
Created January 9, 2017 12:25
Show Gist options
  • Save Keshava11/5518d14473be92eba3aa210065ea70bc to your computer and use it in GitHub Desktop.
Save Keshava11/5518d14473be92eba3aa210065ea70bc to your computer and use it in GitHub Desktop.
Android : Utility to import external database from assets into internal storage
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Utility to import database from assets into the internal storage
*/
public class DbImportUtils {
private static final String DB_DIRPATH = "/data/data/%s/databases/";
private static final String DB_FILEPATH = "/data/data/%s/databases/%s";
private static final int BUFFER_SIZE = 1024;
/**
* Method copies database into a internal storage
*
* @param iContext current context
* @param iDbFileNameAssets filename from the assets
* @return boolean if copying was successful or not
*/
public static boolean copyDatabase(Context iContext, String iDbFileNameAssets) {
boolean fileWriteSuccess = false;
String finalPath = String.format(DB_FILEPATH, iContext.getPackageName(), iDbFileNameAssets);
File file = new File(finalPath);
if (!file.exists()) {
try {
// First check for directories in the along path of file
File fileDir = new File(String.format(DB_DIRPATH, iContext.getPackageName()));
boolean dirCreated = false;
// Creating directory now
if (!fileDir.exists()) {
dirCreated = fileDir.mkdirs();
}
// Directory is created. Check file now
if (dirCreated) {
boolean fileCreated = file.createNewFile();
// File is created. Write data now
if (fileCreated) {
InputStream fis = iContext.getAssets().open(iDbFileNameAssets);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
// Writing bytes into the file
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
//Close the streams
fos.flush();
fos.close();
fis.close();
// All done correctly
fileWriteSuccess = true;
}
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
} else {
fileWriteSuccess = true;
}
return fileWriteSuccess;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment