Skip to content

Instantly share code, notes, and snippets.

@narusemotoki
Created November 13, 2012 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narusemotoki/4066210 to your computer and use it in GitHub Desktop.
Save narusemotoki/4066210 to your computer and use it in GitHub Desktop.
Androidのassetsからデータベースをコピーする
/**
* assetsからデータベースをコピーするためのユーティリティクラス
*
* @author motoki
*/
public class DatabaseUtil {
/**
* コピーを実行する
*
* @param context
* @throws IOException
*/
public static void copy(Context context) throws IOException {
InputStream input = context.getAssets().open(context.getString(R.string.db_name));
OutputStream output = new FileOutputStream(getTargetDb(context));
copy(input, output);
}
/**
* ファイルが存在するか否かでコピー済みかどうかを調べる
*
* @param context
* @return コピー済みならtrue
*/
public static boolean isAlreadyCopied(Context context) {
return getTargetDb(context).exists();
}
private static void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
}
private static File getTargetDb(Context context) {
return context.getDatabasePath(context.getString(R.string.assets_db_name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment