LoginSignup
5
4

More than 5 years have passed since last update.

【Android】assetsフォルダのファイルをローカルストレージにコピーする

Posted at

00. はじめに

設定などをファイルに外だししたい場面がある。
そういう場合では外だししたファイルを別で入れるより、assetsに入れてコピーした方がいい※1。
(apkのファイルサイズが大きくなりすぎる場合は、諦めるしかないが...)

01. ぱーみっしょん

ストレージに書き込むのでパーミッションを設定する必要がある。

<?xml version="1.0" encoding="utf-8"?>
<manifest >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ←追加

    <application >
    </application>
</manifest>

02. こーど

// ファイルセパレータ
public static final String SEPARATOR = File.separator;

// コピー対象のファイル名
private static final String FILE_NAME = "hoge.txt"

// コピー先のディレクトリパス
private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + SEPARATOR + "HogeFile";

private boolean copyAssetsFile() {
    // コピー先のディレクトリ
    File dir = new File(BASE_PATH);

    // コピー先のディレクトリが存在しない場合は生成
    if (!dir.exists()) {
        // ディレクトリの生成に失敗したら終了
        if (!dir.mkdirs()) {
            return false;
        }
    }

    // こぴーしょり
    try {
        InputStream inputStream = getAssets().open(FILE_NAME);
        FileOutputStream fileOutputStream = new FileOutputStream(new File(BASE_PATH + SEPARATOR + FILE_NAME), false);

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

        fileOutputStream.close();
        inputStream.close();
    } catch (IOException e) {
        // 何かテキトーに
        return false;
    }
    return true;
}

03. 注意事項

  • root直下とか、どこでもコピーを置けるわけではなかったはず
    (下回りのcのソースをいじればコピーを置けるように出来たはず※2だけど、アプリ層での開発では関係ない話)

04. 注釈

※1 ... ファイルの入れ忘れを防ぐため。
※2 ... cをあまり触らない人間なので、仕事でやった際のしんどかった記憶しかない。

98. 参考

Androidでassetsのファイルをローカルストレージにコピー | http://nirasan.hatenablog.com/entry/2013/04/24/134018

99. 更新履歴

日付 内容
2018/03/27 投稿
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4