やりたいこと
Androidで、アプリ用ディレクトリ内(/data/data/<package-name>/)に作成されるDBファイルをSDカードにコピーしたい。
サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * DBファイルをSDカードにコピーする * AndroidManifest.xmlにWRITE_EXTERNAL_STORAGEを設定すること * * @param Context context メソッド呼び出し元(Activity等)のContext * @param String dbName コピー元となるデータベースファイル名 * @return コピーに成功した場合true * @throws IOException なんかエラーが起きた場合にthrow */ public static boolean copyDb2Sd(Context context, String dbName) throws IOException { final String TAG = "copyDb2Sd"; //保存先(SDカード)のディレクトリを確保 String pathSd = new StringBuilder() .append(Environment.getExternalStorageDirectory().getPath()) .append("/") .append(context.getPackageName()) .toString(); File filePathToSaved = new File(pathSd); if (!filePathToSaved.exists() && !filePathToSaved.mkdirs()) { throw new IOException("FAILED_TO_CREATE_PATH_ON_SD"); } final String fileDb = context.getDatabasePath(dbName).getPath(); final String fileSd = new StringBuilder() .append(pathSd) .append("/") .append(dbName) .append(".") .append((new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date())) .toString(); Log.i(TAG, "copy from(DB): "+fileDb); Log.i(TAG, "copy to(SD) : "+fileSd); FileChannel channelSource = new FileInputStream(fileDb).getChannel(); FileChannel channelTarget = new FileOutputStream(fileSd).getChannel(); channelSource.transferTo(0, channelSource.size(), channelTarget); channelSource.close(); channelTarget.close(); return true; } |
DDMSからコピーする時はFile Explorerで。