1. 程式人生 > >Android 拷貝Asset目錄下檔案或者資料夾

Android 拷貝Asset目錄下檔案或者資料夾

專案中需要拷貝Asset目錄下的所有檔案,因為Asset目錄是隻讀的,操作起來不是很方便,上網搜了一些方法並不是很有效,記錄一下最後的解決方案:

//path - asset下檔案(夾)名稱  destinationPath - 目的路徑

`private void copyAssetFile(String path,String destinationPath) {
    AssetManager assetManager = mContext.getAssets();
    String assets[] = null;
    try {
        Log.i("tag", "copyFileOrDir() "+path);
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path,destinationPath);
        } else {
            String fullPath =  destinationPath + path;
            Log.i("tag", "path="+fullPath);
            File dir = new File(fullPath);
            if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                if (!dir.mkdirs())
                    Log.i("tag", "could not create dir "+fullPath);
            for (int i = 0; i < assets.length; ++i) {
                String p;
                if (path.equals(""))
                    p = "";
                else
                    p = path + "/";
    if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    copyAssetFileOrDir( p + assets[i],destinationPath);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}`

`private void copyFile(String filename,String destinationPath) {
    AssetManager assetManager = mContext.getAssets();
    InputStream in = null;
    OutputStream out = null;
    String newFileName = null;
    try {
        Log.i("tag", "copyFile() "+filename);
        in = assetManager.open(filename);
        newFileName = destinationPath + filename;
        out = new FileOutputStream(newFileName);
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", "Exception in copyFile() of "+newFileName);
        Log.e("tag", "Exception in copyFile() "+e.toString());
    }
}`