将assets文件中内容复制到SDCard中

来源:互联网 发布:windows已出现关键问题 编辑:程序博客网 时间:2024/05/16 04:55
/** * 作者:Android绝世小菜鸟 *链接:http://www.jianshu.com/p/ec5792496e38 *來源:简书 *著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */public class AssetsCopyer {    private String asset_list_fileName;    private final Context mContext;    private final AssetManager mAssetManager;    private File mAppDirectory;    public AssetsCopyer(Context context, String asset_list_fileName) {        mContext = context;        mAssetManager = context.getAssets();        this.asset_list_fileName = asset_list_fileName;    }    /**     *  将assets目录下指定的文件拷贝到sdcard中     *  @return 是否拷贝成功,true 成功;false 失败     *  @throws IOException     */    public boolean copy() throws IOException {        List<String> srcFiles = new ArrayList<>();        //获取系统在SDCard中为app分配的目录,eg:/sdcard/Android/data/$(app's package)        //该目录存放app相关的各种文件(如cache,配置文件等),unstall app后该目录也会随之删除        mAppDirectory = mContext.getExternalFilesDir(null);        if (null == mAppDirectory) {            return false;        }        //读取assets/$(subDirectory)目录下的assets.lst文件,得到需要copy的文件列表        List<String> assets = getAssetsList();        for( String asset : assets ) {            //如果不存在,则添加到copy列表            if( ! new File(mAppDirectory,asset).exists() ) {                srcFiles.add(asset);            }        }        //依次拷贝到App的安装目录下        for( String file : srcFiles ) {            copy(file);        }        return true;    }    /**     *  获取需要拷贝的文件列表(记录在assets/assets.lst文件中)     *  @return 文件列表     *  @throws IOException     */    protected List<String> getAssetsList() throws IOException {        List<String> files = new ArrayList<>();        InputStream listFile = mAssetManager.open(new File(asset_list_fileName).getPath());        BufferedReader br = new BufferedReader(new InputStreamReader(listFile));        String path;        while (null != (path = br.readLine())) {            files.add(path);        }        return files;    }    /**     *  执行拷贝任务     *  @param asset 需要拷贝的assets文件路径     *  @return 拷贝成功后的目标文件句柄     *  @throws IOException     */    protected File copy( String asset ) throws IOException {        InputStream source = mAssetManager.open(new File(asset).getPath());        File destinationFile = new File(mAppDirectory, asset);        if(destinationFile.exists()){            return destinationFile;        }        destinationFile.getParentFile().mkdirs();        OutputStream destination = new FileOutputStream(destinationFile);        byte[] buffer = new byte[1024];        int nread;        while ((nread = source.read(buffer)) != -1) {            if (nread == 0) {                nread = source.read();                if (nread < 0)                    break;                destination.write(nread);                continue;            }            destination.write(buffer, 0, nread);        }        destination.close();        return destinationFile;    }}

另外,需要在assets文件夹中新建一个assets.lst文件,将需要复制到内存卡的文件名写到该文件中。如下:
这里写图片描述