【问题标题】:copying the entire folder with its contents from assets to internal app files/将整个文件夹及其内容从资产复制到内部应用程序文件/
【发布时间】:2013-03-07 19:30:29
【问题描述】:

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

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

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

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

【问题讨论】:

  • 请描述您遇到的问题。

标签: android file copy assets


【解决方案1】:

希望你能充分利用下面的代码:-

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

}

【讨论】:

  • 这对于从您需要使用 AssetsManager 的资产进行复制没有帮助。
【解决方案2】:

希望对你有帮助

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-01-04
    • 2011-06-25
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多