いつもお世話になっております。
Gregと申します。
アプリ内のファイルをSDカードに保存する方法について
質問させて下さい。
【やりたいこと】
アプリ内(/res/drawable)に配置したファイル(PNGやPDF)を
SDカード内に保存したい。
FileChannelクラスというものがあると知り、
以下のように使用してみました。
------------------------------------------------------------------------
・・・
File inFile = new File("android.resource://" + getPackageName() + "/" + R.drawable.xxxxxx); //「xxxxxx」は/res/drawableに配置したファイル名
File outFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "testname.png");
try {
FileChannel inChannel = new FileInputStream(inFile).getChannel();
FileChannel outChannel = new FileOutputStream(outFile).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
・・・
------------------------------------------------------------------------
この場合LogCatのエラーメッセージには
: java.io.FileNotFoundException: /android.resource:/パッケージ名/2130837506: open failed: ENOENT (No such file or directory)
と出てしまいます。
パスの指定を直接指定して
File inFile = new File("android.resource://" + getPackageName() + "/res/drawable/xxxxxx.png");
としても同様の結果でした。
対象のフォルダにはたしかに配置してあるのに、
上記のようなエラーが出る原因がわかりませんでした。
またFileOutputStreamを使う方法も試してみました。
こちらは例外処理は抜けてエラーは出ないのですが、
ファイルがコピーされませんでした。
------------------------------------------------------------------------
・・・
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "testname.png");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.xxxxxx);
try {
OutputStream stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
・・・
------------------------------------------------------------------------
以上のようにアプリ内のファイルをSDカードに保存することが
実現できていない状況です。
エラー原因、対処の方法について
ご教授頂けないでしょうか。
またより良い方法があれば、教えて頂けないでしょうか。
よろしくお願いします。