将整个文件夹及其内容从资产复制到内部应用程序文件/

时间:2013-03-19 07:56:53

标签: android file copy assets

请建议我将文件夹从资产复制到/ data / data / my_app_pkg / files的最佳方法。

资产(www)中的文件夹包含文件和子文件夹。我想完全复制到我提到的内部应用程序路径的文件/。

我能够成功地将文件从资产复制到内部应用程序文件/路径,但是在复制文件夹时无法执行相同操作,即使是assetmanager.list也没有帮助我,因为它只复制文件,但不是目录/子文件夹。

请建议我做我想做的更好的方法

2 个答案:

答案 0 :(得分:5)

希望在下面的代码中使用完整的代码: -

Copy files from a folder of SD card into another folder of SD card

<强>资产

            AssetManager am = con.getAssets("folder/file_name.xml");


 public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
    throws IOException {

if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
        targetLocation.mkdir();
    }

    String[] children = sourceLocation.list();
    for (int i = 0; i < sourceLocation.listFiles().length; i++) {

        copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
                new File(targetLocation, children[i]));
    }
} else {

    InputStream in = new FileInputStream(sourceLocation);

    OutputStream out = new FileOutputStream(targetLocation);

    // Copy the bits from instream to outstream
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

}

答案 1 :(得分:0)

希望这会有所帮助

private void getAssetAppFolder(String dir) throws Exception{

        {
            File f = new File(sdcardlocation + "/" + dir);
            if (!f.exists() || !f.isDirectory())
                f.mkdirs();
        }
         AssetManager am=getAssets();

         String [] aplist=am.list(dir);

         for(String strf:aplist){
            try{
                 InputStream is=am.open(dir+"/"+strf);
                 copyToDisk(dir,strf,is);
             }catch(Exception ex){


                getAssetAppFolder(dir+"/"+strf);
             }
         }



     }


     public void copyToDisk(String dir,String name,InputStream is) throws IOException{
         int size;
            byte[] buffer = new byte[2048];

            FileOutputStream fout = new FileOutputStream(sdcardlocation +"/"+dir+"/" +name);
            BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);

            while ((size = is.read(buffer, 0, buffer.length)) != -1) {
                bufferOut.write(buffer, 0, size);
            }
            bufferOut.flush();
            bufferOut.close();
            is.close();
            fout.close();
     }