8

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

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

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

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

4

2 回答 2

6

希望在下面的代码中充分利用您:-

将文件从 SD 卡的文件夹复制到 SD 卡的另一个文件夹

资产

            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();
}

}
于 2013-03-19T08:00:21.813 回答
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();
     }
于 2014-04-10T09:49:15.330 回答