public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Context context = this.getBaseContext(); CopyAssets(context,"Device","/sdcard/DeviceFile"); } public static void CopyAssets(Context context, String oldPath, String newPath) { try { String fileNames[] = context.getAssets().list(oldPath);// 获取assets目录下的所有文件及目录名 if (fileNames.length > 0) {// 如果是目录 File file = new File(newPath); file.mkdirs();// 如果文件夹不存在,则递归 for (String fileName : fileNames) { CopyAssets(context, oldPath + "/" + fileName, newPath + "/" + fileName); } } else {// 如果是文件 InputStream is = context.getAssets().open(oldPath); FileOutputStream fos = new FileOutputStream(new File(newPath)); byte[] buffer = new byte[1024]; int byteCount = 0; while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取 fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流 } fos.flush();// 刷新缓冲区 is.close(); fos.close(); } } catch (Exception e) { e.printStackTrace(); } } }
本文介绍了一个简单的Android应用程序,用于从应用的assets文件夹复制文件到设备的SD卡上。通过递归遍历assets中的所有文件和目录,并使用InputStream和FileOutputStream进行文件复制。

被折叠的 条评论
为什么被折叠?



