java - android 怎么复制assets文件夹到本地SD卡?
PHPz
PHPz 2017-04-17 17:09:33
[Java讨论组]

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

PHPz
PHPz

学习是最好的投资!

全部回复(5)
天蓬老师

谢谢大家!已解决
//复制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();
        }
    }
}
怪我咯

文件流的操作,如果是整个文件夹,就需要遍历然后复制到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();
巴扎黑

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

阿神

文件流,子线程

巴扎黑

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号