Copying raw file into SDCard?

谁说我不能喝 提交于 2019-12-17 06:51:58

问题


I've some audio files in my res/raw folder. For some reasons, i want to copy this files to my SDCard When, my application starts.

How can i done this? Anyone guide me?


回答1:


Read from the resource, write to a file on the SD card:

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();
}



回答2:


Copy file from raw to External Storage:

This is a method that i use to do this job, this method receive the resource id, and the name desired for storage, for example:

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

method:

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();
    }

}


来源:https://stackoverflow.com/questions/8664468/copying-raw-file-into-sdcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!