如何将文件从“资产”文件夹复制到sdCard?我有一些文件在assets文件夹。我需要将它们全部复制到一个文件夹中,比如/sdCard/文件夹。我想在线程中完成这个任务。我该怎么做?
3 回答
![?](http://img1.sycdn.imooc.com/533e4bec0001ae5302000200-100-100.jpg)
RISEBY
TA贡献1856条经验 获得超5个赞
创建目录无效 android返回的资产还包含三个文件夹:图像、声音和webkit。 添加了处理大型文件的方法:将扩展名.mp3添加到项目中的资产文件夹中的文件中,在复制过程中,目标文件将没有.mp3扩展名
final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";private void copyFilesToSdCard() { copyFileOrDir(""); // copy all files in assets folder in my project}private void copyFileOrDir(String path) { AssetManager assetManager = this.getAssets(); String assets[] = null; try { Log.i("tag", "copyFileOrDir() "+path); assets = assetManager.list(path); if (assets.length == 0) { copyFile(path); } else { String fullPath = TARGET_BASE_PATH + path; Log.i("tag", "path="+fullPath); File dir = new File(fullPath); if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) if (!dir.mkdirs()) Log.i("tag", "could not create dir "+fullPath); for (int i = 0; i < assets.length; ++i) { String p; if (path.equals("")) p = ""; else p = path + "/"; if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) copyFileOrDir( p + assets[i]); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); }}private void copyFile(String filename) { AssetManager assetManager = this.getAssets(); InputStream in = null; OutputStream out = null; String newFileName = null; try { Log.i("tag", "copyFile() "+filename); in = assetManager.open(filename); if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4); else newFileName = TARGET_BASE_PATH + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", "Exception in copyFile() of "+newFileName); Log.e("tag", "Exception in copyFile() "+e.toString()); }}
- 3 回答
- 0 关注
- 546 浏览
添加回答
举报
0/150
提交
取消