Assert中的内容拷贝到SD卡中

184 阅读1分钟
private void assertToSD() {
        // 获取Assets目录下的文件
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list("");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 遍历文件
        if (files != null) {
            for (String fileName : files) {
                //Log.e(TAG, "名字:" + fileName);
                InputStream is = null;
                OutputStream os = null;

                try {
                    // 定义输入流和输出流
                    is = assetManager.open(fileName);
                    File outFile = new File(getExternalCacheDir(), fileName);
                    //Log.e("mulu", "目录:" + outFile.toString());
                    os = new FileOutputStream(outFile);

                    copyFile(is, os);
                } catch (Exception e) {
                    //Log.e(TAG, "错误:" + e.toString());
                    e.printStackTrace();
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (os != null) {
                        try {
                            os.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }

    }

    private void copyFile(InputStream is, OutputStream os) throws Exception {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) != -1) {
            os.write(buffer, 0, length);
        }
    }