从assets目录复制文件夹和文件,(不只是文件,附demo)

最近要将时钟的一些资源做成文件夹放到apk中,然后用户安装的时候复制到SD卡,由于时间比较紧急,就没有做压缩和解压缩的处理,但是问题来了,文件夹最好的放置位置是assest目录,但是通常我们使用的方法都是open(文件名);来获得流,也就是必须知道整个文件的路径,但是我想的是将整个文件夹复制,android并没有提供这样的方法,纠结了好久,终于发现了一个方法list(目录名)。list里的参数是assets目录下的一个目录名,list(目录名)这会得到该目录下的文件和子文件夹,但是我却得不到文件夹的路径,所以只好遍历其子文件夹再用open(文件名);来一个一个文件复制。

/**
     * 从assets目录下拷贝整个文件夹,不管是文件夹还是文件都能拷贝
     * 
     * @param context
     *            上下文
     * @param rootDirFullPath
     *            文件目录,要拷贝的目录如assets目录下有一个SBClock文件夹:SBClock
     * @param targetDirFullPath
     *            目标文件夹位置如:/sdcrad/SBClock
     */
    public static void copyFolderFromAssets(Context context, String rootDirFullPath, String targetDirFullPath) {
        Log.d(TAG, "copyFolderFromAssets " + "rootDirFullPath-" + rootDirFullPath + " targetDirFullPath-" + targetDirFullPath);
        try {
            String[] listFiles = context.getAssets().list(rootDirFullPath);// 遍历该目录下的文件和文件夹
            for (String string : listFiles) {// 看起子目录是文件还是文件夹,这里只好用.做区分了
                Log.d(TAG, "name-" + rootDirFullPath + "/" + string);
                if (isFileByName(string)) {// 文件
                    copyFileFromAssets(context, rootDirFullPath + "/" + string, targetDirFullPath + "/" + string);
                } else {// 文件夹
                    String childRootDirFullPath = rootDirFullPath + "/" + string;
                    String childTargetDirFullPath = targetDirFullPath + "/" + string;
                    new File(childTargetDirFullPath).mkdirs();
                    copyFolderFromAssets(context, childRootDirFullPath, childTargetDirFullPath);
                }
            }
        } catch (IOException e) {
            Log.d(TAG, "copyFolderFromAssets " + "IOException-" + e.getMessage());
            Log.d(TAG, "copyFolderFromAssets " + "IOException-" + e.getLocalizedMessage());
            e.printStackTrace();
        }
    }
private static boolean isFileByName(String string) {
        if (string.contains(".")) {
            return true;
        }
        return false;
    }
/**
     * 从assets目录下拷贝文件
     * 
     * @param context
     *            上下文
     * @param assetsFilePath
     *            文件的路径名如:SBClock/0001cuteowl/cuteowl_dot.png
     * @param targetFileFullPath
     *            目标文件路径如:/sdcard/SBClock/0001cuteowl/cuteowl_dot.png
     */
    public static void copyFileFromAssets(Context context, String assetsFilePath, String targetFileFullPath) {
        Log.d(TAG, "copyFileFromAssets ");
        InputStream assestsFileImputStream;
        try {
            assestsFileImputStream = context.getAssets().open(assetsFilePath);
            FileHelper.copyFile(assestsFileImputStream, targetFileFullPath);
        } catch (IOException e) {
            Log.d(TAG, "copyFileFromAssets " + "IOException-" + e.getMessage());
            e.printStackTrace();
        }
    }

复制过程的log:

 

猜你喜欢

转载自flycatdeng.iteye.com/blog/2156551
今日推荐