web-dev-qa-db-ja.com

生ファイルをSDカードにコピーしますか?

res/rawフォルダにいくつかのオーディオファイルがあります。なんらかの理由で、このファイルをSDカードにコピーしたいのですが、アプリケーションが起動します。

どうすればこれを行うことができますか?誰かが私を導きますか?

20
Praveenkumar

リソースから読み取り、SDカード上のファイルに書き込みます。

InputStream in = getResources().openRawResource(R.raw.myresource);
FileOutputStream out = new FileOutputStream(somePathOnSdCard);
byte[] buff = new byte[1024];
int read = 0;

try {
   while ((read = in.read(buff)) > 0) {
      out.write(buff, 0, read);
   }
} finally {
     in.close();
     out.close();
}
43
Nikolay Elenkov

Rawから外部ストレージにファイルをコピーします。

これは私がこの仕事をするために使用するメソッドであり、このメソッドはリソースIDと、ストレージに必要な名前を受け取ります。次に例を示します。

copyFiletoExternalStorage(R.raw.mysound, "jorgesys_sound.mp3");

方法:

private void copyFiletoExternalStorage(int resourceId, String resourceName){
    String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
    try{
        InputStream in = getResources().openRawResource(resourceId);
        FileOutputStream out = null;
        out = new FileOutputStream(pathSDCard);
        byte[] buff = new byte[1024];
        int read = 0;
        try {
            while ((read = in.read(buff)) > 0) {
                out.write(buff, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
2
Jorgesys