复制Assets 下文件到SD 卡

方法1

代码块
public void start(){  //开始copy文件到sd卡
AssetManager mAm = context.getAssets();//初始化资产目录管理器
    getFileCopy(mAm.open(assetsfilename),sdfilename);
}
  //拷贝过程
    private void getFileCopy(InputStream is,String mUrl) {
        File file = new File(mUrl);

        InputStreamReader isr = null;
        BufferedReader br = null;
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);

            String ss;
            String ioInfo = "";
            while ((ss=br.readLine())!=null){
                ioInfo+=ss;
            }
            bw.write(ioInfo);
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("hhjhgjsa:"+e.getMessage());
        }finally {
            try {
                if(bw!=null){
                    bw.close();
                }
                if(osw!=null){
                    osw.close();
                }

                if(fos!=null){
                    fos.close();
                }

                if(br!=null){
                    br.close();
                }

                if(isr!=null){
                    isr.close();
                }
                if (is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

方法2

public void start (){
            getAssetsFileCopy(item.getAssetsfile(),item.getLocalfileurl());
}

    private void getAssetsFileCopy(String assetsName, String mUrl) {
        InputStream  is=   context.getClassLoader().getResourceAsStream("assets/"+assetsName);
        File file = new File(mUrl);
        FileOutputStream fos = null;

        try {
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n= is.read(buffer))!=-1){
                fos.write(buffer,0,n);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("hhjhgjsa:"+e.getMessage());
        }finally {
            try {

                if(fos!=null){
                    fos.close();
                }
                if (is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

改方法主要适用于大文件的copy

方法一适用于小文件,少量文件的复制,但是大文件和批量文件复制会导致OOM,因为是一次性读取

你可能感兴趣的:(复制Assets 下文件到SD 卡)