1

需要复制Assert的文件夹到本地SD卡,有40M的大小,请问怎么做呀??

leonhy 113
2016-02-23 提问
5 个回答
1

已采纳

谢谢大家!已解决
//复制assets大文件到本地SD卡

public static void CopyAssets(Context context, String assetDir, String dir) {
    String[] files;
    try {
        files = context.getResources().getAssets().list(assetDir);
    } catch (IOException e1) {
        return;
    }
    File mWorkingPath = new File(dir);
    // if this directory does not exists, make one.
    if (!mWorkingPath.exists()) {
        if (!mWorkingPath.mkdirs()) {

        }
    }

    for (int i = 0; i < files.length; i++) {
        try {
            String fileName = files[i];
            // we make sure file name not contains '.' to be a folder.
            if (!fileName.contains(".")) {
                if (0 == assetDir.length()) {
                    CopyAssets(context, fileName, dir + fileName + "/");
                } else {
                    CopyAssets(context, assetDir + "/" + fileName, dir+ fileName + "/");
                }
                continue;
            }
            File outFile = new File(mWorkingPath, fileName);
            if (outFile.exists())
                outFile.delete();
            InputStream in = null;
            if (0 != assetDir.length())
                in = context.getAssets().open(assetDir + "/" + fileName);
            else
                in = context.getAssets().open(fileName);
            OutputStream out = new FileOutputStream(outFile);

            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0

文件流的操作,如果是整个文件夹,就需要遍历然后复制到SD卡下指定目录。

单个文件大概是这个样子,整个目录就递归遍历下(文件夹目录必须存在,不存在需要手动创建目录):

InputStream is = context.getResources().getAssets().open("你的文件")
FileOutputStream fos = new FileOutputStream("指定的文件目录");
byte[] buffer = new byte[8192];
int count;
while ((count = is.read(buffer)) > 0){
    fos.write(buffer, 0, count);
}
fos.close();
is.close();
0

单个文件40M应该是会有问题的,编译可能都通过不了。最好分割成小文件(1M),RandomAccessFile再组装写到SD卡上。思路是这样的,具体的IO操作就不细表了。

0

文件流,子线程

0

真的不是叫assets文件夹么。。然后遍历在子线程里写到SD卡就好了。

撰写答案

推广链接