Android 複製res/raw中的檔案到指定目錄
public class FileStorageHelper { private static final String SEPARATOR = File.separator;//路徑分隔符 /** * 複製res/raw中的檔案到指定目錄 * @param context 上下文 * @param id 資源ID * @param fileName 檔名 * @param storagePath 目標資料夾的路徑 */ public static void copyFilesFromRaw(Context context, int id, String fileName, String storagePath){ InputStream inputStream=context.getResources().openRawResource(id); File file = new File(storagePath); if (!file.exists()) {//如果資料夾不存在,則建立新的資料夾 file.mkdirs(); } readInputStream(storagePath + SEPARATOR + fileName, inputStream); } /** * 讀取輸入流中的資料寫入輸出流 * * @param storagePath 目標檔案路徑 * @param inputStream 輸入流 */ public static void readInputStream(String storagePath, InputStream inputStream) { File file = new File(storagePath); try { if (!file.exists()) { // 1.建立通道物件 FileOutputStream fos = new FileOutputStream(file); // 2.定義儲存空間 byte[] buffer = new byte[inputStream.available()]; // 3.開始讀檔案 int lenght = 0; while ((lenght = inputStream.read(buffer)) != -1) {// 迴圈從輸入流讀取buffer位元組 // 將Buffer中的資料寫到outputStream物件中 fos.write(buffer, 0, lenght); } fos.flush();// 重新整理緩衝區 // 4.關閉流 fos.close(); inputStream.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
參考自: https://blog.csdn.net/u013693649/article/details/61626359
歡迎掃碼加入QQ群一起學習討論。【QQ群:930039263】
