java - android 怎么复制assets文件夹到本地SD卡?
PHPz
PHPz 2017-04-17 17:09:33
0
5
397

需要复制Assert的文件夹到本地SD卡,有40M的大小,请问怎么做呀??

PHPz
PHPz

学习是最好的投资!

reply all (5)
Peter_Zhu

Thank you everyone! Solved
//Copy assets large files to local SD card

public static void CopyAssets(Context context, String assetDir, String dir) { String[] files; try { files = context.getResources().getAssets().list(assetDir); } catch (IOException e1) { return; } File mWorkingPath = new File(dir); // if this directory does not exists, make one. if (!mWorkingPath.exists()) { if (!mWorkingPath.mkdirs()) { } } for (int i = 0; i < files.length; i++) { try { String fileName = files[i]; // we make sure file name not contains '.' to be a folder. if (!fileName.contains(".")) { if (0 == assetDir.length()) { CopyAssets(context, fileName, dir + fileName + "/"); } else { CopyAssets(context, assetDir + "/" + fileName, dir+ fileName + "/"); } continue; } File outFile = new File(mWorkingPath, fileName); if (outFile.exists()) outFile.delete(); InputStream in = null; if (0 != assetDir.length()) in = context.getAssets().open(assetDir + "/" + fileName); else in = context.getAssets().open(fileName); OutputStream out = new FileOutputStream(outFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
    刘奇

    For file stream operations, if it is an entire folder, it needs to be traversed and copied to the specified directory under the SD card.

    A single file looks like this, and the entire directory is traversed recursively (the folder directory must exist, if it does not exist, you need to create the directory manually):

    InputStream is = context.getResources().getAssets().open("你的文件") FileOutputStream fos = new FileOutputStream("指定的文件目录"); byte[] buffer = new byte[8192]; int count; while ((count = is.read(buffer)) > 0){ fos.write(buffer, 0, count); } fos.close(); is.close();
      巴扎黑

      A single file of 40M may cause problems, and the compilation may not pass. It is best to split it into small files (1M), assemble it with RandomAccessFile and write it to the SD card. The idea is this, the specific IO operations will not be listed in detail.

        阿神

        File stream, sub-thread

          巴扎黑

          Isn’t it really called aassetsfolder? . Then just traverse and write to the SD card in the sub-thread.

            Latest Downloads
            More>
            Web Effects
            Website Source Code
            Website Materials
            Front End Template
            About us Disclaimer Sitemap
            php.cn:Public welfare online PHP training,Help PHP learners grow quickly!