安卓复制res/raw中的文件到指定目录

╰半橙微兮° 2023-10-04 10:52 121阅读 0赞
  1. /**
  2. * 复制res/raw中的文件到指定目录
  3. *
  4. * @param context 上下文
  5. * @param id 资源ID R.raw.文件名
  6. * @param fileName 文件名
  7. * @param storagePath 目标文件夹的路径
  8. */
  9. public static void copyFilesFromRaw(Context context, int id, String fileName, String storagePath) {
  10. InputStream inputStream = context.getResources().openRawResource(id);
  11. File file = new File(storagePath);
  12. if (!file.exists()) {//如果文件夹不存在,则创建新的文件夹
  13. file.mkdirs();
  14. }
  15. readInputStream(storagePath + File.separator + fileName, inputStream);
  16. }
  17. /**
  18. * 读取输入流中的数据写入输出流
  19. *
  20. * @param storagePath 目标文件路径
  21. * @param inputStream 输入流
  22. */
  23. public static void readInputStream(String storagePath, InputStream inputStream) {
  24. File file = new File(storagePath);
  25. try {
  26. if (!file.exists()) {
  27. // 1.建立通道对象
  28. FileOutputStream fos = new FileOutputStream(file);
  29. // 2.定义存储空间
  30. byte[] buffer = new byte[inputStream.available()];
  31. // 3.开始读文件
  32. int lenght = 0;
  33. while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
  34. // 将Buffer中的数据写到outputStream对象中
  35. fos.write(buffer, 0, lenght);
  36. }
  37. fos.flush();// 刷新缓冲区
  38. // 4.关闭流
  39. fos.close();
  40. inputStream.close();
  41. }
  42. } catch (IOException e) {
  43. XLog.printExceptionInfo(e);
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,121人围观)

还没有评论,来说两句吧...

相关阅读

    相关 文件目录

    安卓文件目录 /data目录下的文件,物理上存放在我们通常所说的内部存储里面 /storage目录下的文件,物理上存放在我们通常所说的外部存储里面 /system用于